1

我有两个模型,我想通过我的搜索表单进行搜索

<%= form_tag({:controller => 'search', :action => 'search'}, {:method => 'get', :remote => true })  do |select| %>
<%= label_tag :search, "Enter Keywords Here" %>
<%= text_field_tag :search, params[:search] %>

<%= label_tag :country, "Search by Country" %>
<%= collection_select(:country, :country_id, Country.all, :id, :name, :prompt => 'Please Select') %>

<%= label_tag :difficulty, "Search by Difficulty" %>
<%= select_tag :difficulty, options_for_select([['Beginner'],['Intermediate'],['Expert']]), {:prompt => 'Please Select'} %>

<%= label_tag :preperation_time, "Search by preperation time" %>
<%= select_tag :preperation_time, options_for_select([['15..30'],['30..60'],['60..120']]), {:prompt => 'Please Select'} %><br>

<%= submit_tag "Search", :class => "searchbutton" %>
<% end %>

我的理解是,如果我希望能够搜索所有列,我的 sql 语句应该如下所示

SELECT column dish_name, difficulty, preparation_time FROM Recipe LEFT JOIN Country ON Recipe.dish_name = Country.name AND Recipe.difficulty = Country.name AND Recipe.preparation_time = Country.name

这可能是完全错误的想法,我想要实现的是能够通过一个参数或最多 4 个参数进行搜索

我不知道如何把它变成 Rails 语法,目前我有

q = "%#{params[:search]}%"
@countrysearch = Recipe.includes(:country).where("dish_name LIKE ? OR countries.name LIKE ? OR difficulty LIKE ? OR preperation_time LIKE?", q, q, q,q )

如果有人能指出我正确的方向,那将不胜感激

4

1 回答 1

1

不了解

如果您想更好地了解您正在使用此方法调用做什么,您可以随时使用to_sql以打印生成的 SQL 查询。

您还可以检查由 rails 和控制台退化的日志。

左连接示例

@result = Recipe.joins("LEFT OUTER JOIN countries ON countries.id = recipes.country_id").select

但也是可能的,最好按照你的方式做

@result = Recipe.includes(:country)

打印查询

puts @result.to_sql

构建查询

countrysearch = Recipe.includes(:country).arel_table
countrysearch = countrysearch.or(countrysearch[:country].eq(params[:search][:country])) if params[:search].has_key?(:country)
#...
countrysearch = countrysearch.or(countrysearch[:difficulty].eq(params[:search][:difficulty])) if params[:search].has_key?(:difficulty)

参考

请检查以下参考中的替代方案:

  1. 导轨/arel
  2. 215:Rails 3 中的高级查询

希望这对你有帮助!!

于 2012-11-13T18:38:59.157 回答