问题描述
我通过协会的has_many如下:
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
我希望它会允许我这样做,例如 user.bookmarks查询(纸)
。然而,当我尝试了上面,类
呈现的#&LT的价值;用户:0x000001017f2090>
(基本上用户
在上面的调用),我似乎不能够调用一个简单的字符串的关联。
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.
推荐答案
我不认为这可以在的has_many
调用来实现。我只希望在我的用户定义一个实例方法
类来获得该功能:
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
不知道这个方法的实现,但问题是,我不认为你可以有一个的has_many
接受参数。
另一件事你可以看看是范围。在这种情况下,你可能要定义你的收藏
模型 for_category
范围,允许这样的:
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')
这篇关于Rails4 HAS_MANY通过与参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!