簡體   English   中英

在Rails中搜索具有多個參數的表格航班

[英]Search form flights with multiple params in Rails

我正在填寫旅行社搜索表格。 我需要用戶能夠輸入起點和目的地,並讓搜索表單返回所有符合那些條件的航班。

我正在嘗試使用RoR做到這一點,但是我是新手,希望有人可以幫助我。 先感謝您

這就是我嘗試過的。

我在視圖中的搜索表單是這樣的

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

這是飛行模型對象的代碼

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

這是飛行控制器操作中的代碼

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

這是我的資料庫。 目前我只打了兩場,但我會增加更多

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'

您不能一次訪問params hash的兩個鍵。 您需要單獨檢查並傳遞參數。

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