[英]Searching through linked models in rails3
After following the railscast for creating a search engine, my code looks like this for search titles, and descriptions of posts: 在遵循了创建搜索引擎的规则之后,我的代码看起来像这样的搜索标题和帖子描述:
def self.search(search)
if search
where("LOWER (description) LIKE ? OR LOWER (title) LIKE ?", "%#{search.downcase}%" , "%#{search.downcase}%")
else
scoped
end
end
The post table, has_many tags though, and I'd like this search query to search tags as well. 帖子表,虽然有has_many标签,但我也希望此搜索查询也可以搜索标签。 Is this possible?
这可能吗?
Try 尝试
def self.search(search)
if search
includes(:tags).where("LOWER (description) LIKE ? OR LOWER (title) LIKE ? OR tags.name LIKE ?", "%#{search.downcase}%" , "%#{search.downcase}%", "%#{search.downcase}%")
else
scoped
end
end
This will do a LIKE
on the name
property of the tags. 这将做一个
LIKE
上的name
标签的属性。 Edit it to suit your needs. 编辑它以满足您的需求。
Recommend having a tag_list stored on the post model itself, which will make searching trivial. 建议将post_model本身存储在tag_list中,这将使搜索变得简单。 @Dogbert's answer works just as well, the following contains the query to one table.
@Dogbert的答案也一样有效,以下内容包含对一张表的查询。
def post
before_update :set_tag_list
def set_tag_list
self.tag_list = tags.map{|tag| tag.name}.join(', ')
end
end
Then you can include the tag_list in your search query and not have to join many models together. 然后,您可以将tag_list包含在搜索查询中,而不必将许多模型结合在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.