1

I have a model named AnswerConnection, who has two foreign keys from Answer model: answer_1 and answer_2.

In my Answer model I have defined:

has_many :connections, through: :answer_connections, source: :answer_2

However, the relationship is simmetrycal: if answer_1 is connected to answer_2, answer_2 is connected to answer_1. This means that when I search the connections of an specific answer, I need to check if its present in answer_1 or answer_2 field.

There is possible to define a relationship attending this (like if I could define two values in :source parameter)?

rwehresmann
  • 1,108
  • 2
  • 11
  • 27
  • sounds like you want to use has_and_belongs_to_many, or possibly has_many_through if you want to put other fields in your AnswerConnection model – elc Mar 30 '17 at 16:37
  • Yes, My `Answer` model have a `has many through` relationship with `AnswerConnection` model. However, from my Answer model I would like to get its connections, respecting this simmetrycal relationship described. – rwehresmann Mar 30 '17 at 16:50
  • 1
    oh sorry, I missed the crucial point that it's a self reference association. See here: http://stackoverflow.com/questions/19770888/rails-self-join-scheme-with-has-and-belongs-to-many – elc Mar 30 '17 at 17:01

1 Answers1

2

I don't think you can set 2 sources, but if I understood it correctly you could do something like:

has_many :connections_1, through: :answer_connections, source: :answer_1
has_many :connections_2, through: :answer_connections, source: :answer_2

def connections
  connections_1.merge(connections_2) # intersection
  # or connections_1.or(connections_2) for union
end
gabrielhilal
  • 10,660
  • 6
  • 54
  • 81
  • Please note that while this efficiently gives you a combined list, other operations (eg removing a connection) will still require extra code. So depending on future needs, even though this looks simpler than the answer I linked to above where all connection are automatically recorded both ways--it could well end up being more complicated in the end. – elc Mar 30 '17 at 21:12
  • 1
    This answer is giving me a multiple association error on the Inner Join, any ideas? `ActiveRecord::StatementInvalid: PG::DuplicateAlias: ERROR: table name "connections" specified more than once` – CHawk Jan 19 '18 at 17:43