Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

has_one through association with condition

I have 3 relevant tables/models. I would like to retrieve the user which has organized a party, given a Party record, a join table with a boolean organized column, and a users table.

My best attempt so far (this one makes the most sense to me after much fiddling). I've omitted the irrelevant columns.

class Party
  # party_id

  has_many   :parties_users
  has_many   :users, through: :parties_users, source: :user
  has_one    :organizer,
             -> { where organizer: true },
             through: :parties_users,
             source: :user

class PartiesUser
  # party_id
  # user_id
  # organized:bool

  belongs_to :party
  belongs_to :user

class User
  # user_id
  has_many : parties_users

The above setup raises the following error, which I honestly don't fully understand: ActiveRecord::HasOneThroughCantAssociateThroughCollection (Cannot have a has_one :through association 'Party#organizer' where the :through association 'Party#parties_users' is a collection. Specify a has_one or belongs_to association in the :through option instead.)

I know I can do this via an instance method, but given the frequency types of use, my app would massively benefit from having this as an association.

like image 419
Dan Avatar asked Mar 19 '18 15:03

Dan


People also ask

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is a polymorphic association in Rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.

What is Has_and_belongs_to_many?

Rails offers two different ways to declare a many-to-many relationship between models. The first way is to use has_and_belongs_to_many, which allows you to make the association directly: The second way to declare a many-to-many relationship is to use has_many :through.


1 Answers

As the error message says, you can't have a has_one through a has_many.

You could (instead) do it this way if the organizer flag is on the join record...

has_many :parties_users
has_many :users, through: :parties_users, source: :user
has_one :main_party_user, -> {where organizer: true}, class_name: 'PartiesUser'
has_one :organizer, through: :main_party_user, class_name: 'User'
like image 88
SteveTurczyn Avatar answered Oct 07 '22 10:10

SteveTurczyn