Rails Data Modelling: How to establish relationships when 2 Objects "Share" the same has_many list?

65 views Asked by At

In a nutshell, when I create a Transaction Record it has two foreign keys. for the two users that participate in a Transaction, ie:

enter image description here

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 Transactions for either of the two Users.

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?

Thanks in advance.

3

There are 3 answers

6
Tom Copeland On BEST ANSWER

If you have two user ids and want to query Transaction on some combination of them, you can use an or clause:

>> 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">]>
0
neo7 On

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
}
1
neo7 On

Use polymorfic assossiations that can solve this issue I am in the train now will provide you with code or you can start looking up for this task and good luck ;)