[英]ruby on rails - Search form with select_tag
I have 2 models, Post and Location, where location has_many posts and post belongs_to location. 我有2个模型,即Post和Location,其中location has_many个帖子和post includes_to location。 I want to make a search function with 3 conditions.
我想使用3个条件进行搜索。 With the following code it did not return any thing in my testing.
使用以下代码,它在我的测试中未返回任何内容。
View search.html: 查看search.html:
<%= form_tag search_posts_path, :method => 'get' do %>
<p>
<%= text_field_tag :title, params[:title] %>
<%= text_field_tag :company, params[:company] %>
<%= select_tag :location_id, options_from_collection_for_select(Location.all, :id, :name, params[:location_id]), include_blank: true %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
Controller post_controller.rb: 控制器post_controller.rb:
def search
title = params[:title]
company = params[:company]
location_id = params[:location_id]
@posts = Post.search(title, company, location_id)
end
Model Post.rb 模型Post.rb
def self.search(title, company, location_id)
return scoped unless title.present? || company.present? || location_id.present?
where(['title LIKE ? AND company LIKE ? AND location_id = ?', "%#{title}%", "%#{company}%", "%#{location_id}%"])
end
There is no need of '%' for location_id if location_id is not a string.Hope this helps. 如果location_id不是字符串,则不需要'%'作为location_id,希望这会有所帮助。
Model Post.rb 模型Post.rb
def self.search(title, company, location_id)
return scoped unless title.present? || company.present? || location_id.present?
where(['title LIKE ? AND company LIKE ? AND location_id = ?', "%#{title}%", "%#
{company}%", location_id])
end
You don't need % around our location_id and you shouldn't convert it to string 您不需要在location_id周围加上%,也不应将其转换为字符串
Few debugging tips for future reference: 少量调试技巧可供将来参考:
a) Check whether this actually should return anything - does such a record exists in current db? a)检查它是否实际上应该返回任何内容-当前数据库中是否存在这样的记录?
b) Try runnig the query through console. b)尝试通过控制台运行查询。 You can use
.to_sql
on relation object to see what SQL is executed 您可以在关系对象上使用
.to_sql
来查看执行了什么SQL
c) If no results, try break your where conditions and check which bit works and which doesn't (I'm almost sure the problem is related with data types for location_id) c)如果没有结果,请尝试打破您的where条件,并检查哪个位有效,哪个无效(我几乎可以确定问题与location_id的数据类型有关)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.