没有外键的 ActiveRecord 关联
我正在尝试建立用户之间的关系模型。用户可以发起关系,或者从另一个用户接收关系。因此,数据库中的关系表具有外键“initiator_id”和“recipient_id”。
现在,我可以使用以下关联来计算用户发起或接收的关系:
has_many :initiated_relations, :foreign_key => :initiator_id, :class_name => 'Relation', :dependent => :destroy
has_many :received_relations, :foreign_key => :recipient_id, :class_name => 'Relation', :dependent => :destroy
我想做的是建立一个关联,该关联将获取属于用户的所有关系(发起或接收)。尝试以下方法不起作用,并抱怨缺少“user_id”字段:
has_many :relations, :conditions => 'recipient_id = #{id} or initiator_id = #{id}'
How can I create an Association that is only based on the criteria field, without waiting for the defaultforeign_key?或者是否有一种完全不同的方法来解决这个问题?
I am trying to build a relationship model between users. A user can either initiate a relation, or receive a relation from another user. Therefore, the relations table in the db has the foreign keys "initiator_id" and "recipient_id".
Now, I can figure what relations the user initiated or received using the following associations:
has_many :initiated_relations, :foreign_key => :initiator_id, :class_name => 'Relation', :dependent => :destroy
has_many :received_relations, :foreign_key => :recipient_id, :class_name => 'Relation', :dependent => :destroy
What I am trying to do, is build an association that will fetch me all relations that belong to a user (either initiated or received). Trying the following does not work, and complains about the lack of "user_id" field:
has_many :relations, :conditions => 'recipient_id = #{id} or initiator_id = #{id}'
How can I create an association that is solely based on the conditions field, without looking for the default foreign_key? Or is there perhaps a completely different approach to solving this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从你的评论到@neutrino的回答我明白,你只需要这个“关系”来进行只读操作。如果您使用 Rails 3,您可以利用它使用延迟获取的事实。
where()
方法返回ActiveRecord::Relation
对象,您可以稍后修改该对象。所以你可以定义一个这样的方法:然后你可以这样做:
From your comments to @neutrino's answer I understand, that you only need this "relation" for read only operations. If you're on Rails 3 you can utilize the fact, that it uses lazy fetching. The
where()
method returnsActiveRecord::Relation
object, which you can later modify. So you can define a method like this:And then you can do:
好吧,我可以考虑使用
finder_sql
来实现这一点:除此之外,您可以编写一个方法来返回两个关系关联的统一数组,但您将失去关联的优势接口(唷)。
也许有人会想出更好的解决方案。
Well, I can think of using
finder_sql
for that:Apart from that, you can just write a method that will return a united array of the two relations associations', but you will lose the advantage of an association interface (phew).
Perhaps someone will come up with a better solution.