如何在模型Rails中的select_tag上使用if语句

时间:2012-08-09 14:46:21

标签: ruby-on-rails ruby ruby-on-rails-3 jruby

好的,所以当我提交表单时,这些是通过我的浏览器传递的参数:

{"Search"=>"Job Letter and CD #",
"utf8"=>"✓",
"search"=>"g",
"commit"=>"Search"}

基本上我需要做的是在我的模型测试中第一个参数“搜索”。 例如:

if Search == "Job Letter and CD #"
..do stuff..
elsif Search == "something else"
..do different stuff..
else
..do something..

我一直在为此烦恼,无法弄明白。我的红宝石代码在下面我可能会删除一些“结束”和类似的东西以节省空间。

index.html.erb

<form class="well form-search right">
<%= select_tag "Search", options_for_select([ "Job Letter and CD #", "Date", "Cust",            "Job", "Date shipped", "Date billed", "Billed by" ], params[:search]) %>
<%= form_tag reports_path, :method => 'get' do %> 
<%= text_field_tag :search, params[:search], :class=> "form-search", :align => "right" %>
<%= submit_tag "Search", [ :JOBLETTER_CD_NUMBER, :DATE, :CUST, :JOB, :DATE_SHIPPED, :DATE_BILLED, :billed_by ] => nil, :class => "btn btn-success", :align => "right" %>

report.rb模型

      def self.search(search)  
if Search == 'Job Letter and CD #'
  where('JOBLETTER_CD_NUMBER LIKE ?', "%#{search}%") 
elsif Search == 'Date'
  where('DATE ?', "%#{search}%")
else
  scoped  
end
end  

1 个答案:

答案 0 :(得分:1)

我猜您需要将2个参数传递给模型中的搜索功能

def self.search(what_to_search,search_string)
  if what_to_search == 'Job Letter and CD #'
     where('JOBLETTER_CD_NUMBER LIKE ?', "%#{search_string}%") 
  elsif what_to_search == 'Date'
     where('DATE ?', "%#{search_string}%")
  else
      scoped  
  end
end

以这种方式从您的控制器调用搜索

Search.search(params[:Search],params[:search])