问题描述
我有3个相关的表格/模型。我想检索组织聚会的用户,给定Party记录,带有布尔值 organized
的联接表,以及一个用户
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
上述设置引发了以下错误,老实说我不完全理解:
ActiveRecord :: HasOneThroughCantAssociateThroughCollection(Cannot有一个has_one:through关联 Party#organizer,其中:through关联 Party#parties_users是一个集合。在:through选项中指定has_one或belongs_to关联。)
我知道我可以通过实例方法来执行此操作,但是考虑到使用的频率类型,将其作为关联可以大大受益于我的应用。
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.
推荐答案
如错误消息所述,您无法通过has_many获得has_one。
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'
这篇关于has_one通过与条件关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!