[英]Rails ActiveRecord: two has_one relationships between the same models
I have a model, Project, that has 2 associations to the same model: 我有一个模型Project,该模型具有与同一模型的2个关联:
belongs_to :source_connection, class: Connection
belongs_to :destination_connection, class: Connection
That works fine - I can access connection methods through project without any issues. 效果很好-我可以通过项目访问连接方法而没有任何问题。
I'm a little confused on how to do the inverse, however. 但是,我对如何进行逆运算有些困惑。 I started with a rather optimistic: 我开始比较乐观:
has_one :project
on the Connection model, and unsurprisingly, it throws an 在连接模型上,毫不奇怪,它会抛出一个
ActiveModel::MissingAttributeError: can't write unknown attribute 'connection_id'
error when I try to access the project from the connection itself. 尝试从连接本身访问项目时发生错误。
If anyone knows how I can declare the association on the connection side, I'd be appreciative. 如果有人知道如何在连接端声明关联,我将不胜感激。 Cheers. 干杯。
Associations 社团协会
You will probably be best looking at the foreign_key
arguments for ActiveRecord Associations: 您可能最好查看ActiveRecord关联的foreign_key
参数:
#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 you have is that since you're not using the foreign_key
option in your associations, Rails will be looking for the standard foreign_key
associations inside your schema (typically model_name_id
). 您遇到的问题是,由于您没有在关联中使用foreign_key
选项,因此Rails会在您的模式(通常是model_name_id
)中寻找标准的foreign_key
关联。
-- -
Error 错误
can't write unknown attribute 'connection_id' 无法写入未知属性“ connection_id”
I don't know why it's complaining about writing , but the reason is likely that you don't have the correct foreign key set up for your association. 我不知道为什么它抱怨写作 ,但是原因很可能是您没有为关联设置正确的外键。 Typically, Rails will be looking for the model_name_id
- but since you're not, you'll need to set the relative key in your models (as demonstrated) 通常,Rails会寻找model_name_id
但由于您不在,您需要在模型中设置相对键(如所示)
has_one :project, foreign_key: 'source_connection_id'
Rails is looking for connection_id as the error says, as you've used source_connection and destination_connection you need to tell it to use the correct foreign key to look it up. 如错误所示,Rails正在寻找connection_id,因为您已经使用了source_connection和destination_connection,所以需要告诉它使用正确的外键进行查找。
You might want to define them as: 您可能需要将它们定义为:
has_one :source_project, foreign_key: 'source_connection_id'
has_one :destination_project, foreign_key: 'destination_connection_id'
Because you won't be able to call them both project. 因为您将无法同时调用这两个项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.