Rails: Validating association after save?

前端 未结 4 2148
孤城傲影
孤城傲影 2021-02-08 02:51

I have a User model which has many roles. Roles contains a user_id field, which I want to validate_presence_of

The is

4条回答
  •  别那么骄傲
    2021-02-08 03:33

    I think you can get around the validation problem if you change your code to look like this:

    @user = User.new(params[:user])
    @user.roles.new(:name => 'Peon') unless @user.has_roles?
    if @user.save
      # ...
    

    If that doesn't work, you could try changing you validation to this:

    class Role < ActiveRecord::Base
      belongs_to :user
      validates :user_id, :presence => true, :unless => Proc.new() {|r| r.user}
    end
    

提交回复
热议问题