Ruby on rails RubyonRails-带select_标记的搜索表单
我有两个模型,Post和Location,其中Location有许多Post,Post属于Location。我想做一个有3个条件的搜索函数。对于下面的代码,它在我的测试中没有返回任何东西 看法 search.html:Ruby on rails RubyonRails-带select_标记的搜索表单,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,我有两个模型,Post和Location,其中Location有许多Post,Post属于Location。我想做一个有3个条件的搜索函数。对于下面的代码,它在我的测试中没有返回任何东西 看法 search.html: <%= form_tag search_posts_path, :method => 'get' do %> <p> <%= text_field_tag :title, params[:title] %>
<%= 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 %>
Model 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
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
如果location\u id不是字符串,则location\u id不需要“%”。希望这有帮助 Model 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
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
您不需要在我们的位置\u id周围使用%s,也不应该将其转换为字符串 以下几点调试技巧供将来参考: a) 检查是否应该返回任何内容-当前数据库中是否存在此类记录 b) 尝试通过控制台运行查询。您可以在关系对象上使用
.to_sql
,查看执行的是什么sql
c) 如果没有结果,请尝试打破where条件,检查哪个位有效,哪个不有效(我几乎可以肯定问题与位置id的数据类型有关)您可以在终端(服务器日志)中看到它对搜索的查询吗?参数:{“utf8”=>“✓", "标题“=>”键“、”公司“=>”tra“、”位置id“=>”1”}[1m[35mPost Load(3.0ms)[0m选择“posts”。*从“posts”中选择(标题如“%key%”,公司如“%tra%”,位置id为“%1%”)您好,Gopal,还是一样…您是否将location_id作为posts表上的字符串?还有一个问题:如何将优先级选项添加到select_标记中?您是指select标记中选项的顺序吗?类似于此。使用location.order()?如何将分页添加到搜索结果中?以及对搜索结果的限制。