如果存在两个参数,我希望搜索并找到结果,但我会被发送到car_show_path,但应该有结果。
模型
class Car < ActiveRecord::Base
def self.search(car_number, car_model)
where(['car_number = ? AND car_model = ?', "%#{car_number}%", "%#{car_model}%"])
end
end
控制器显示
@search = Car.search(params[:car_number], params[:car_model])
if @search.present?
@search
else
redirect_to car_path, notice: "Not a valid combination"
end
表格
<%= simple_form_for :search, url: car_show_path do |f| %>
<%= f.input :car_number, :collection => @car.collect {|c| [c.number]}, :include_blank => false %>
<%= f.input :car_model, placeholder: "Car Model" %>
<%= f.button :submit, 'Generate', class: 'btn' %>
<% end %>
答案 0 :(得分:8)
你做错了。如果查看服务器日志中生成的params哈希值,您可以看到类似:search => {:car_model => "value", :car_number => "Value"}
的内容。这意味着无法使用:car_model
和:car_number
检索params[:car_model]
和params[:car_number]
的值,而应使用params[:search][:car_model]
和params[:search][:car_number]
@search = Car.search(params[:search][:car_number], params[:search][:car_model])
if @search.present?
@search
else
redirect_to car_path, notice: "Not a valid combination"
end
答案 1 :(得分:3)
我看到了您提供的代码。我相信你写的代码需要一些改进。所以我重新编写了可以解决您的问题并实现目标的代码。这是:
#/app/models/car.rb
class Car < ActiveRecord::Base
def self.search(cn, cm)
where('car_number = ? AND car_model = ?', cn, cm)
end
end
#/app/controllers/cars_controller.rb
class CarsController < ApplicationController
def search
@result = Car.search params[c_number], params[c_modal]
end
end
#/app/views/cars/search.html.erb
#you can generate similar form with simple_form_for
<form action="/search" method="/get" >
<input type="text" name="c_number"
<input type="text" name="c_modal">
<input type="submit" value="search">
</form>
<% if !@result.any? %>
Not a valid combination
<% end %>
<% @result.each do |r|%>
<%= r.car_number %>
<%= r.car_modal %>
<% end %>
#/config/routes.rb
get "/search" => "cars#search"
注意:上面的代码是我最好的做法,并没有在本地执行。
希望有所帮助!!!
答案 2 :(得分:-1)
您将相同的值放入要发送到搜索方法的查询参数的两个占位符中。这似乎不对。