[英]Custom includes association in rails
I have the following table我有下表
Users(user_id, name, last_name)
Relationships(user_id, spouse_id)
I want to run the following query我想运行以下查询
person = Relationships.includes(:person).where(:name => 'David')
But I don't want the related person to be associated by the user_id
.但我不希望相关人员与user_id
相关联。 I would rather it be associated by the spouse_id
only for this specific query.我宁愿它只与这个特定查询的spouse_id
相关联。
Rails is perfectly content to allow multiple associations to the same table, providing they use a different foreign key. Rails 完全满足于允许多个关联到同一个表,前提是它们使用不同的外键。
In this case, you'd have something like this:在这种情况下,你会有这样的事情:
class User
has_many :relationships
has_many :spouses, class_name: "Relationship", foreign_key: :spouse_id
end
User.first.spouses
would then be a collection of all relationships where the user's id
was present in the spouse_id
field. User.first.spouses
将是所有关系的集合,其中用户的id
出现在spouse_id
字段中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.