Thursday, March 10, 2016

Rails 4 search Multiple Params

Leave a Comment

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 %> 

3 Answers

Answers 1

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 

Answers 2

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 !@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" 

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

Hope that helps!!!

Answers 3

You are putting the same values into both placeholders from the query parameter that is being sent to your search method. That doesn't seem right.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment