Activerecord has_many :through through multiple models

后端 未结 5 1449
忘掉有多难
忘掉有多难 2020-12-31 12:00

I\'m trying to access all comments from a given user with user.comments. The query is to go through two different models, which likely both return results. My r

5条回答
  •  一生所求
    2020-12-31 12:46

    Since we couldn't use has_many, through here because comments come from both of organisers and participants. I just think there are 2 solutions here:

    Solution #1 Define comments method:

    class User < ActiveRecord::Base
      def comments
        Comment.joins([{organiser: :user}, {participant: :user}])
               .where(users: {id: self.id})
      end
    end
    

    So then your query to find comments is:

    User.first.comments
    

    Solution #2 Use scope in Comment

    class Comment < ActiveRecord::Base
      scope :from_user, -> (user) { 
        joins([{organiser: :user}, {participant: :user}]).where(users: {id: user.id}) 
      }
    end
    

    So your query will be like:

    user = User.first
    comments = Comment.from_user(user)
    

提交回复
热议问题