Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 search Multiple Params

I'm looking to search and find results if two params exist, but i'm getting sent to car_show_path, but should have results.

Model

class Car < ActiveRecord::Base
  def self.search(car_number, car_model) 
    where(['car_number = ? AND car_model = ?', "%#{car_number}%", "%#{car_model}%"])
  end
end

Controller Show

 @search = Car.search(params[:car_number], params[:car_model])
   if @search.present?
       @search
    else
     redirect_to car_path, notice: "Not a valid combination"
    end

Form

<%= 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 %>
like image 295
DollarChills Avatar asked May 28 '15 23:05

DollarChills


2 Answers

You are doing it wrong. If you look into the params hash generated in the server log, you can see something like this :search => {:car_model => "value", :car_number => "Value"}. That means the values of :car_model and :car_number cannot be retrieved with params[:car_model] and params[:car_number], instead you should use params[:search][:car_model] and 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
like image 165
Pavan Avatar answered Nov 11 '22 07:11

Pavan


I see the code you have provided. I believe the code you have written need some improvement. So I have re-written code which may solve your issue and bring to your goal. Here it is :

#/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 [email protected]? %>
  Not a valid combination
<% end %>

<% @result.each do |r|%>
  <%= r.car_number %>
  <%= r.car_modal %>
<% end %>


#/config/routes.rb

get "/search" => "cars#search"

Note : Above code is best of my practice and didn't executed locally.

Hope that helps!!!

like image 25
Anand Soni Avatar answered Nov 11 '22 09:11

Anand Soni