has_one through association with condition

ε祈祈猫儿з 提交于 2019-12-10 13:20:55

问题


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.


回答1:


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'


来源:https://stackoverflow.com/questions/49366460/has-one-through-association-with-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!