Activerecord has_many :through through multiple models

后端 未结 5 1426
忘掉有多难
忘掉有多难 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:40

    I believe your associations would be confused, as user.comments wouldn't know whether it's going through Participant or Organiser, so the best option would be to declare two different joins (with different names):

    http://guides.rubyonrails.org/association_basics.html#self-joins

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-31 12:49

    I found a solution after many tries. You can use a scope with param in your last has_many sentence in the User model:

    has_many :comments, -> (user) {where organiser: user.organisers}, through: :participants
    

    The "user" param represet the User object whom is calling the comments method.

    0 讨论(0)
  • 2020-12-31 12:53

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

    Basically you can still change the foreign key to accept the self.id automatically with Rails here

    User.first.comments
    
    class User
      has_many :comments, -> { joins([{ organiser: :user }, { participant: :user }]) }, through: :participants, foreign_key: "users.id"
    end
    
    0 讨论(0)
  • 2020-12-31 13:00

    Could you do something as simple as:

    has_many :comments, -> { joins(:participant, :organizer) }, class_name: 'Comment'
    

    This should return all comments that have a Participant or Organizer User, since Rails tends to default joins to an inner join. You may not even need that :class_name argument.

    0 讨论(0)
提交回复
热议问题