在我的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
放映,我需要能够搜索显示,并存储显示&#39 ; s 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
什么代码可以让我的搜索工作?
答案 0 :(得分:0)
问题是where
没有返回记录,它返回可以枚举或链接的关系,而是要使用find
或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