Search code examples
ruby-on-railsrubyruby-on-rails-2

Text field tag search issue


Hello everybody i'm trying to search a column from another table with id hide using text_field_tag

In my view policy_vehicles i have text_field_tag and want to search by motor

My tables

Vehicles
      |id|       |motor|    |plate|
    integer    varchar(255)  varchar(255)
       1        MOTOR1        PLATE1
       2        MOTOR2        PLATE2
       3        MOTOR3        PLATE3

Policy_vehicles
   |id|       |vehicle_id| 
    integer      integer
     1              1 
     2              2
     3              3
     4              2

Here is my controller

class PolicyManagement::PolicyController < ApplicationController

  def generate_print_per_vehicle
      @motor =Vehicle.find(:all,:conditions=>['motor =?' ,params[:search_motor] ] )
      @policies= PolicyVehicle.find(:all,:conditions=>['vehicle_id= ?',params[:search_motor] ] ) 
  end

end

Here is my model

class PolicyVehicle < ActiveRecord::Base
  belongs_to :vehicle
end

class Vehicle < ActiveRecord::Base
  has_many :policy_vehicles
end

Here is my view where i'm trying to find by a column from another table

<% form_tag :controller=>"policy_management/policy",:action=>"generate_print_per_vehicle" do %>
 Motor:
   <%= text_field_tag "search_motor",params[:search_motor] %>
   <%= submit_tag "Buscar", :name => nil %>
<% end %>

My logs

 Vehicle Load (0.1ms)   SELECT * FROM `vehicles` WHERE (motor ='4D56UCCR5811') 
 PolicyVehicle Load (0.3ms)   SELECT * FROM `policy_vehicles` WHERE (vehicle_id= '4D56UCCR5811') 

It should be search like this

 SELECT * FROM `vehicles` WHERE (motor ='4D56UCCR5811' and id =1) 
 SELECT * FROM `policy_vehicles` WHERE (vehicle_id= '1') 

I tried this but is not working

 #controller
 @vehicle = Vehicle.find(:all,:conditions=>['motor =?' ,params[:search_motor] ])
 @policies = PolicyVehicle.find(:all, :conditions => ['vehicle_id = ?  ', @vehicle.id])

#logs
Vehicle Load (17.2ms)   SELECT * FROM `vehicles` WHERE (motor ='4D56UCCR5811') 
PolicyVehicle Load (0.3ms)   SELECT * FROM `policy_vehicles` WHERE (vehicle_id = 70353663367520 ) 

Well i did a select_tag, but i want to write the motor, not select like this

<%= select_tag "search_motor",options_for_select(@vehicle.collect {|t| [t.motor.to_s ,t.id]}, params[:search_motor].to_i )  %>

Please someone can help me ? I will really appreciate help


Solution

  • If you are using find with :all specified, you'll get an array of vehicles back, even if that array is size 1. So instead of asking for @vehicle.id you'd have to ask for something like @vehicle[0].id:

    PolicyVehicle.find(:all, :conditions => ['vehicle_id = ?  ', @vehicle[0].id])
    

    But if you don't need the @motor array for any other purpose, you should be able use one query with :join to go directly to the record you want:

    PolicyVehicle.find(:all, :joins => :vehicle, :conditions => ['motor =?',params[:search_motor]])