我试图弄清楚如何做这样的事情:
event = Event.new
loc = Location.new
loc.name = "test"
loc.save
event.locations << loc
event.save!
事件和位置具有多对多关系的地方。但是,我不断收到此错误:
ActiveRecord::RecordInvalid: Validation failed: Event locations is invalid
如果我先保存事件,这很好用,但是在我正在工作的上下文中我没有该选项。
这是我的模型:
class Event < ActiveRecord::Base
#belongs_to :user
has_many :event_locations
has_many :locations, :through => :event_locations
accepts_nested_attributes_for :locations
end
class EventLocation < ActiveRecord::Base
belongs_to :event
belongs_to :location
validates_presence_of :event
validates_presence_of :location
accepts_nested_attributes_for :location
end
class Location < ActiveRecord::Base
has_many :event_locations
has_many :events, :through => :event_locations
end
现在我发现连接模型 EventLocation 上的验证会导致这个问题。
我不应该验证吗?有不同的方法吗?