I have two models, AssetEvent
and Subsystem
, and a join model between them AssetEventSubsystem
. They look like this:
RehabEvent < AssetEvent
has_many :asset_event_subsystems
has_many :subsystems, :through => :asset_event_subsystems
AssetEventSubsystem
belongs_to :rehab_event, :class_name => 'AssetEvent', :foreign_key => "asset_event_id"
belongs_to :subsystem
Subsystem
belongs_to :asset_type
When I try to run RehabEvent.new.asset_event_subsystems.build
, I get back a ActiveRecord::UnknownAttributeError: unknown attribute: rehab_event_id
, which is confusing, because I thought that should have been taken care of by the foreign_key
option in the join model.
How do I make rails use the column in my database ( asset_event_id
) instead of the default?
Looks like u need that: ?
RehabEvent < AssetEvent
has_many :asset_event_subsystems
has_many :subsystems, :through => :asset_event_subsystems,
:foreign_key => "asset_event_id"
AssetEventSubsystem
belongs_to :rehab_event, :class_name => 'AssetEvent', :foreign_key => "asset_event_id"
belongs_to :subsystem
Subsystem
has_many :asset_event_subsystems
has_many :rehab_events, :through => :asset_event_subsystems
belongs_to :asset_type
And btw, i dont know your project, but can you use just has_and_belongs_to_many ?
您需要在您的has_many
关联中以及您的belongs_to
定义foreign_key
:
has_many :asset_event_subsystems, foreign_key: 'asset_event_id'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.