Rails4 has_many via parameters

I have an association has_many through

like this:

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

      

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

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

      

I was hoping this would allow me to make queries like user.bookmarks("papers")

. However, when I try to do this it category

takes a value #<User:0x000001017f2090>

(mostly user

in the call above) and I can't seem to be able to name the link with a simple string.

Any suggestion on how this can be achieved? Thank you so much.

+3


source to share


1 answer


I don't think this can be achieved in a challenge has_many

. I would just define an instance method in my class User

to get this 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, I don't think you can have has_many

one that takes parameters.



Another thing you might want to learn is scopes . In this case, you may need to define an area for_category

on your model Bookmark

allowing something like:

user.bookmarks.for_category('papers')

      

+1


source







All Articles