[英]Why isn't my search method working in Ruby on Rails?
在我的Ruby on Rails應用程序中,我有一個影院系統,並且我試圖返回屏幕,當用戶搜索顯示時顯示。
要顯示搜索下拉列表,我在_application.html.erb中使用此代碼:
<%= render( :partial => '/screen_lookup', :locals => {:showings => @showings = Showing.all, :my_path => '/screens/display_screens_by_showing' })%>
這將從_screen_lookup.html.erb呈現搜索:
<%= form_tag my_path, :method=>'post', :multipart => true do %>
<%= select_tag ('showings_id'),
options_from_collection_for_select(@showings, :id, :showing_times, 0 ),
:prompt => "Showings" %>
<%= submit_tag 'Search' %>
<% end %>
並使用screens_controller中的display_screens_by_showing:
def display_screens_by_showing
@screens = Screen.showing_search(params[:showing_id])
if @screens.empty?
# assign a warning message to the flash hash to be displayed in
# the div "feedback-top"
flash.now[:alert] = "There are no films of that genre."
# return all products, in alphabetical order
@screens = Screen.all
end
render :action => "index"
end
這使用screen.rb模型中的方法進行搜索:
def self.showing_search(showing_id)
screen = Showing.where("id = ?", showing_id).screen_id
self.where("id = ?", screen)
end
現在,我遇到的問題是,由於一個放映belongs_to
屏幕,並且屏幕has_many
看房,我需要能夠搜索的顯示,並存儲在一個變量顯示的screen_id搜索的屏幕表現是有,我在模型中嘗試過:
screen = Showing.where("id = ?", showing_id).screen_id
self.where("id = ?", screen)
但我得到的錯誤是:
NoMethodError in ScreensController#display_screens_by_showing
undefined method `screen_id' for #<ActiveRecord::Relation []>
這些是模型關系:
showing.rb:
class Showing < ActiveRecord::Base
belongs_to :screen
end
screen.rb:
class Screen < ActiveRecord::Base
has_many :showings
end
什么代碼可以讓我的搜索工作?
問題是, where
沒有返回記錄,它返回一個可以枚舉或鏈接的關系,而你想使用find
或find_by
返回單個記錄,這find_by
where + first
screen = Showing.find(showing_id).screen_id
這有點像做
screen = Showing.where(id: showing_id).first.screen_id
如果你想傳遞一個哈希,你可以使用find_by
,就像這樣
screen = Showing.find_by(id: showing_id).screen_id
PS:
我不確定你在做什么,但我認為這兩行可以合並為一個查詢(不確定它應該返回什么,但我假設一個屏幕)
def self.showing_search(showing_id)
Showing.find(showing_id).screen
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.