Friday, 15 July 2011

Rails ActiveRecord: two has_one relationships between the same models -



Rails ActiveRecord: two has_one relationships between the same models -

i have model, project, has 2 associations same model:

belongs_to :source_connection, class: connection belongs_to :destination_connection, class: connection

that works fine - can access connection methods through project without issues.

i'm little confused on how inverse, however. started rather optimistic:

has_one :project

on connection model, , unsurprisingly, throws

activemodel::missingattributeerror: can't write unknown attribute 'connection_id'

error when seek access project connection itself.

if knows how can declare association on connection side, i'd appreciative. cheers.

associations

you best looking @ foreign_key arguments activerecord associations:

#app/models/project.rb class project < activerecord::base belongs_to :source_connection, class: "connection", foreign_key: "source_connection_id" belongs_to :destination_connection, class: "connection", foreign_key: "destination_connection_id" end #app/models/connection.rb class connection < activerecord::base has_many :projects, foreign_key: "source_connection_id" end

the issue have since you're not using foreign_key alternative in associations, rails looking standard foreign_key associations within schema (typically model_name_id).

--

error

can't write unknown attribute 'connection_id'

i don't know why it's complaining writing, reason don't have right foreign key set association. typically, rails looking model_name_id - since you're not, you'll need set relative key in models (as demonstrated)

ruby-on-rails activerecord

No comments:

Post a Comment