2
votes

Has anybody had any luck having a has_one go through a has_many relationship in the same model. I keep getting

ActiveRecord::HasOneThroughCantAssociateThroughCollection: Cannot have a has_one :through association

It seems like it would be easy take a set of has_many results and filter it down by a specific key and call it a has_one relationship.

Using rails 3.2.12

Here is my associations right now participation is a different model.

has_one :original_participation, :through => :participation

has_one :original_participant, :through => :original_participants, :foreign_key => "organization_id"

has_many :original_participants,
  :through => :original_participation,
  :source => :participants

I need to go through this last association and filter it down by organization_id.

ActiveRecord::HasOneThroughCantAssociateThroughCollection: Cannot have a has_one :through association 'Surveys::Participant#original_participant' where the :through association 'Surveys::Participant#original_participants' is a collection. Specify a has_one or belongs_to association in the :through option instead.

1
Could you post your models?gotqn
You are saying that you have one :original_participant from a collection of :original_participants. There is no way to know which is THE original_participant. If you want just one, then in your method you could just use original_participants.firstlilwupster
Well the original_participants is a collection and through that collection I want to find the one with the current objects oganization_id. This may not even be possible normally we would just put into a scope but we are making this working with thinking sphinx and the version we are using doesn't support joining to scopes. We are going to take it from another way though to avoid this messy lookup.wallerjake
I do not think there is anything that is limiting organization_id to be unique, so you can create a function such as: def original_participant original_participants.where(organization_id: id).first end Syntax might be off and I'm not sure where the org_id is coming from but hopefully it makes sense.lilwupster

1 Answers

2
votes

With has_one you should not need :through There is no need for an intermediary relationship.

If I think I know what you're trying to do you have a hierarchy of tests:

has_one test_parent, :class_name => "Test", foreign_key: "child_test"

has_many tests

to call them:

@my_array_of_children = tests

@my_parents_id = test.id

etc.