开发者

Rails filter by SQL search in different model

In my Photos view there is an option to search using a text_field. I wanted to add an option to "search" by clicking on predefined tags. Perhaps a search is not the best way to do this.

This is the method for search in my model:

def self.search(search)
  if search
    where('name or description or tag.name LIKE ?', "%#{search}%")
  else
    scoped
  end
end

I'm not sure that I am calling this correctly either... But these are the links I create in the index view for photos:

<% @tags.each do |tag| %>
  <%= link_to tag.name, :search => tag.name, :class => "tag" %>
<% end %>

Tags are not in the photo table, but have HABTM relation with photos. I can normally call them though simply with @photo.tags.name or something similiar. A开发者_开发技巧nyway, when I click a tag it spits back a SQLite3::SQLException: no such column: tag.name: SELECT COUNT(*) FROM "photos" WHERE (name or description or tag.name LIKE '%landscape%'). Any thoughts? Perhaps there is a better way to do this in the first place?


In order to find by a field that is in the tags table you have to make a join with it. To make it change your search method to this:

def self.search(search)
  if search
    joins(:tags).where('name or description or tags.name LIKE ?', "%#{search}%")
  else
    scoped
  end
end


Coming with your own solution to common problems is a great way to learn, however, I'd recommend that you delegate the tags job to a specialized gem like: https://github.com/mbleigh/acts-as-taggable-on, so you can keep focused on your business.

Also, using a relational model to save tags is somewhat overkill: a comma-separated list of tags should be enough for most cases.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜