nemo
nemo

Reputation: 485

Rails4 has_many through with parameters

I have a has_many through association as follows:

has_many :bookmarks, -> {where('actions.bookmark=true')},
    :through => :actions,
    :source => :object

what I'd like to do is to extend the above to pass categories for the objects bookmarked. Something like the following:

has_many :bookmarks, -> (category) {where('actions.bookmark=true and objects.category=?', category)},
    :through => :actions,
    :source => :object

I was hoping it would allow me to do queries such as user.bookmarks("papers"). However, when I try the above, category takes on the value of #<User:0x000001017f2090> (basically user in the call above) and I don't seem to be able to call the association with a simple string.

Any suggestion on how this could be achieved? Thanks very much.

Upvotes: 3

Views: 1501

Answers (1)

Mischa
Mischa

Reputation: 43298

I don't think this can be achieved in the has_many call. I'd just define an instance method in my User class to get that functionality:

def bookmarks_for_category(category)
  bookmarks.includes(:objects).where('objects.category = ?', category)
end

Not sure about the implementation of this method, but the point is that I don't think you can have a has_many that accepts parameters.

Another thing you could look into is scopes. In this case you may want to define a for_category scope on your Bookmark model, allowing something like:

user.bookmarks.for_category('papers')

Upvotes: 1

Related Questions