Rails: Validating association after save?

前端 未结 4 2209
孤城傲影
孤城傲影 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:47

    For anyone Googling for a solution to this problem for a has_many :through association, as of 5/December/2013 the :inverse_of option can't be used in conjunction with :through (source). Instead, you can use the approach suggested by @waldyr.ar. For example, if our models are set up as follows:

    class User < ActiveRecord::Base
      has_many :roles
      has_many :tasks, through: roles
    end
    
    class Role < ActiveRecord::Base  
      belongs_to :user  
      belongs_to :task  
    end
    
    class Task < ActiveRecord::Base
      has_many :roles
      has_many :users, through: roles
    end
    

    We can modify our Role class as follows to validate the presence of both task and user before saving

    class Role < ActiveRecord::Base  
      belongs_to :user  
      belongs_to :task  
      before_save { validates_presence_of :user, :task }
    end
    

    Now if we create a new User and add a couple tasks like so:

    >> u = User.new  
    >> 2.times { u.tasks << Task.new }
    

    Running u.save will save the User and the Task, as well as transparently build and save a new Role whose foreign keys user_id and task_id are set appropriately. Validations will run for all models, and we can go on our merry way!

提交回复
热议问题