Search code examples
ruby-on-railsassociations

has_many association with scope in Rails will not accept arguments


I have an Ad class which has_many messages. I want to be able to do ad.messages(user) to get all the messages to a given user on that ad. I currently have

has_many :messages, ->(user) { where(to_id: user.id) }

But this isn't working and I can't figure out why. Without the scope it works as expected and returns all message, or if I don't have the argument and hard-code a user ID it also works. The code as it is however, gives me wrong number of arguments (given 1, expected 0).


Solution

  • Hacking has_many makes it not work how it is supposed to do.

    You can just define a method on your class

    class Ad
      def messages(user_id)
        Message
          .where(ad_id: self.id)
          .where("to_id = :user_id OR from_id = :user_id", user_id: user_id)
      end
    end
    
    # somewhere else
    
    Ad.first.messages(some_user_id)