[英]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.