【问题标题】:Rails Model Associations with has_many, through, class_name and where clause与 has_many、through、class_name 和 where 子句的 Rails 模型关联
【发布时间】:2017-06-10 16:20:30
【问题描述】:

寻求有关 Rails 协会的一点帮助。我有三个模型。用户、与会者和会议,我想根据他们的角色(在与会者模型下)返回参加会议的用户。但是我不知道如何使用 where 子句返回用户。

我的代码当前返回 Attendee,然后我查找 User 对象,但如果有办法让它返回 User 对象,我会喜欢它,而无需在调用后查找它.

class Meeting

  has_one :owner, -> { where role: 'owner' }, class_name: 'Attendee'
  has_one :mentor, -> { where role: 'mentor' }, class_name: 'Attendee'
  has_many :mentees, -> { where role: 'mentee' }, class_name: 'Attendee'

end

我的其他联想如下

  has_many :users, through: :attendees
  has_many :attendees, dependent: :destroy

这可能吗?非常感谢任何输入。

【问题讨论】:

    标签: ruby-on-rails model-associations


    【解决方案1】:

    我不确定我是否理解正确。你试过了吗?这是你需要的吗?

    class Meeting
      has_one :owner, -> { where role: 'owner' }, class_name: 'Attendee'
      has_one :mentor, -> { where role: 'mentor' }, class_name: 'Attendee'
      has_many :mentees, -> { where role: 'mentee' }, class_name: 'Attendee'
    
      has_one :owner_user, through: :owner, source: :user
      has_one :mentor_user, through: :mentor, source: :user
      has_many :mentees_users, through: :mentees, source: :user
    end
    

    【讨论】:

    • 感谢 Chumakoff,不知道事情是这样的!它只是在每一行的末尾缺少一件事source: :user
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 2014-03-21
    相关资源
    最近更新 更多