在我的应用程序中,我有一个简单的关系,其中用户有很多事件:
class User < ApplicationRecord
has_many :events, foreign_key: 'created_by', dependent: :destroy
accepts_nested_attributes_for :events
end
class Event < ApplicationRecord
belongs_to :user, foreign_key: 'created_by', inverse_of: :events
validates :created_by, presence: true
end
当我尝试与某些事件一起创建用户时,我收到验证错误&#34; Companies.created by can not is blank&#34; 。
我的params哈希看起来像那样:
{"user"=>{"events_attributes"=>[{"name"=>"disney show"}]}}
当我删除validates :created_by, presence: true
时,一切都按预期工作。任何帮助将不胜感激!
答案 0 :(得分:1)
尝试使用inverse_of:
class User < ApplicationRecord
has_many :events, foreign_key: 'created_by', inverse_of: :user, dependent: :destroy
accepts_nested_attributes_for :events
end
您的Event
记录将使用指向User
的当前外键创建。