分段多态关联中的对象

时间:2015-10-20 08:52:13

标签: ruby-on-rails

我有一个多态关联,我现在要做的就是获得所有这些,但是按照他们属于谁来划分它们。

我的问题:

  has_many :question_participants
  has_many :users, through: :question_participants,
                   source: :questionable, source_type: 'User'
  has_many :groups, through: :question_participants,
                    source: :questionable, source_type: 'Group'


# question can be assigned to Company, Group, User
class QuestionParticipant < ActiveRecord::Base
  belongs_to :question
  belongs_to :questionable, polymorphic: true
end

现在我要做的是f.ex循环遍历属于用户的所有问题,或者属于某个组的所有问题。我如何实现这一目标。

1 个答案:

答案 0 :(得分:0)

使用范围。 在您的question.rb中,添加以下内容:

scope :user_questions, -> { includes(:question_participants).where(question_participants: { source_type: 'User' }) }
scope :group_questions, -> { includes(:question_participants).where(question_participants: { source_type: 'Group' }) }

然后,您可以通过Question.user_questionsQuestion.group_questions访问。