[英]Rails Data Modelling: How to establish relationships when 2 Objects “Share” the same has_many list?
In a nutshell, when I create a Transaction
Record it has two foreign keys . 简而言之,当我创建
Transaction
记录时,它具有两个外键 。 for the two users that participate in a Transaction
, ie: 对于参与
Transaction
的两个用户,即:
Now, What I would like to know with your kind help, is How do I establish the relationship(s) between: User
and Transaction
Models, so that I can easily retrieve ALL the Transaction
s for either of the two User
s. 现在,我想在您的帮助下知道如何建立
User
和Transaction
模型之间的关系 ,以便我可以轻松地检索两个User
的所有Transaction
。
Something like: 就像是:
user_one = User.find(1)
user_two = User.find(2)
user_one.transactions # returns all Transactions where user_one.id ==
# user_one_id Or user_one.id == user_two_id
user_two.transactions # returns all Transactions where user_two.id ==
# user_one_id Or user_two.id == user_two_id
What's the best way to achieve this? 实现此目标的最佳方法是什么? Is it best to establish foreign keys in the Transaction Model in this case?
在这种情况下,最好在事务模型中建立外键吗? Or is this a problem to be solved via
ActiveRecordQuery
only? 还是仅通过
ActiveRecordQuery
解决这个问题?
Thanks in advance. 提前致谢。
If you have two user ids and want to query Transaction
on some combination of them, you can use an or
clause: 如果您有两个用户ID,并想以它们的某种组合查询
Transaction
,则可以使用or
子句:
>> Transaction.where(user_one_id: 1).or(Transaction.where(user_two_id: 2))
Transaction Load (4.3ms) SELECT "transactions".* FROM "transactions" WHERE ("transactions"."user_one_id" = $1 OR "transactions"."user_two_id" = $2) LIMIT $3 [["user_one_id", 1], ["user_two_id", 2], ["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Transaction id: 1, user_one_id: 1, user_two_id: 2, created_at: "2017-09-12 23:25:39", updated_at: "2017-09-12 23:25:39">]>
this is sample code 这是示例代码
class Transaction
def move
return ""
end
end
class User1 < Transaction
def move
return 'User1 move: X'
end
end
class User2 < Transaction
def move
return'User2 move: O'
end
end
transactions = [User1.new, User2.new]
transactions.each {|tran|
print tran.move
}
使用可以解决此问题的多态关联,我现在在火车上将为您提供代码,或者您可以开始寻找此任务,祝您好运;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.