【发布时间】:2015-02-21 12:05:00
【问题描述】:
在我的 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 []>
这些是模型关系:
显示.rb:
class Showing < ActiveRecord::Base
belongs_to :screen
end
screen.rb:
class Screen < ActiveRecord::Base
has_many :showings
end
什么代码可以让我的搜索工作?
【问题讨论】:
-
所以当我运行
Screen.showing_search(5)时,我期望得到什么回报?属于 id = 5 的屏幕的所有放映对吗? -
是的,但应该只有一个屏幕
-
是的,我编辑了我的评论,最后一个听起来对吗?
-
有点,我知道它试图通过 id 查找显示,但我想要做的是然后选择显示的 screen_id,并在屏幕表中搜索具有该 screen_id 的屏幕
标签: sql ruby-on-rails ruby select where