简体   繁体   English

在Rails中搜索具有多个参数的表格航班

[英]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. 我正在尝试使用RoR做到这一点,但是我是新手,希望有人可以帮助我。 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. 您不能一次访问params hash的两个键。 You need to check and pass the parameters individually. 您需要单独检查并传递参数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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