简体   繁体   中英

Search form flights with multiple params in Rails

I'm doing a trip agency search form. I need the user to be able to enter an origin and a destination and have the search form return all the flights that match those conditions.

I'm trying to do it with RoR but I'm new to it and I hope someone can help me. Thank you in advance¡¡

This is what I have tried.

My search form in the view is like this

<%= form_tag summary_path, :method => 'get' do %>
    <p>Origin</p>
    <%= label_tag(:origin) %>
    <%= text_field_tag (:origin), params[:origin] %>
    <p>Destination</p>
    <%= label_tag(:destination) %>
    <%= text_field_tag (:destination), params[:destination] %>

    <%= submit_tag "Search", name: 'nil' %>
    <% end %>

This is the code of Flight Model Object

def self.search(origin,destination)
    #The result of the search has to be all the flights that have the origin and destinations entered by user
    where("origin like ?", "%#{origin}%").where("destination like ?", "%#{destination}%")
end

This is the code in the Flight Controller action

def show
    if params[:origin, :destination]
        @flights = Flight.search(params[:origin, :destination])
    else
        @alert = "Sorry, there are no results"
    end
end

And this is my databse. By the moment I just have two fights but I'll add more

Flight.create origin: 'Madrid', destination: 'Paris', price: 95, from_date: DateTime.new(2014, 11, 06, 10, 30), to_date: DateTime.new(2014, 11, 06, 12, 30), duracion: 2, aerolinea: 'DMS Trips', country: 'España'
Flight.create origin: 'Paris', destination: 'Madrid', price: 95, from_date: DateTime.new(2014, 11, 06, 10, 30), to_date: DateTime.new(2014, 11, 06, 12, 30), duracion: 2, aerolinea: 'DMS Trips', country: 'Francia'

You cannot access two keys of the params hash at once. You need to check and pass the parameters individually.

if params[:origin] && params[:destination]
  @flights = Flight.search(params[:origin], params[:destination])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM