Record select where near match depends on previous direct match in Rails 3
Is there a smart way to have only a single select for the near_matches? If I find an exact match for the name I am looking for, I don't want that in the list of near matches.
@match = Item.where("name = '" + params[:name] + "'开发者_运维知识库").first
if @match
@near_matches = Item.where("name like '%" + params[:name] + "%' and id != " + @match.id.to_s)
else
@near_matches = Item.where("name like '%" + params[:name] + "%'")
end
Not quite what you asked for, but this tightens it up a bit:
@match = Item.find_by_name params[:name]
@near_matches = Item.where('name LIKE ?', "%#{params[:name]}%")
@near_matches = @near_matches.where('id != ?', @match.id) if @match
This works because queries are lazy -- they're not actually run until they need to be.
The question mark is for the bind variable, which is more secure.
精彩评论