Creating nested models - Rails 3.1

后端 未结 2 726
南笙
南笙 2021-01-23 19:02

I am trying to create 3 nested models at once, and have trouble with my validations.

These are my models:

class UserEntity < ActiveRecord::Base
  ha         


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-01-23 19:45

    You need to have accepts_nested_attributes_for and inverse_of relations defined.

    class UserEntity < ActiveRecord::Base
      has_many   :users, :dependent => :restrict, :autosave => true, :inverse_of => :users_entity
      accepts_nested_attributes_for :users
    end
    
    class User < ActiveRecord::Base
      has_many    :user_login_services, :dependent => :destroy, :autosave => true, :inverse_of => :user
      belongs_to  :user_entity, :inverse_of => :users
      accepts_nested_attributes_for :user_login_services
    end
    
    class UserLoginService < ActiveRecord::Base
      belongs_to :user, :inverse_of => :users_login_services
      validates :user, :presence => true 
    end
    

    I also switched validates :user_id to validates :user assuming you want to validate the existence of the associated user and not just that the UserLoginService has a user_id.

提交回复
热议问题