【问题标题】:Why isn't my search method working in Ruby on Rails?为什么我的搜索方法在 Ruby on Rails 中不起作用?
【发布时间】: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


【解决方案1】:

问题是where 不返回记录,它返回一个可以枚举或链接的关系,而不是您想使用findfind_by 返回单个记录,这相当于to 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

【讨论】:

  • 这给出了错误:TypeError in ScreensController#display_screens_by_showing can't convert nil into String
  • 好的,那么这个方法应该返回什么,nil 是什么? showing_id?
  • 好吧,我希望它返回的是所选放映所在的屏幕。我遇到的问题是一个屏幕有很多放映,所以我不知道如何找到放映的屏幕在
  • 您能否给出问题的模型定义,只是模型名称和关系,用于显示和屏幕
猜你喜欢
  • 2017-07-11
  • 1970-01-01
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
  • 2023-01-06
  • 1970-01-01
  • 2020-02-28
  • 2015-06-07
相关资源
最近更新 更多