【问题标题】:Trouble getting basic searchlogic plugin code to work in Rails App无法让基本的 searchlogic 插件代码在 Rails App 中工作
【发布时间】:2010-02-07 03:16:33
【问题描述】:

我的 rails 应用程序抛出此错误:

为 nil 调用 id,它会错误地为 4 -- 如果你真的想要 nil 的 id,请使用 object_id

我正在尝试制作一个允许用户按“国家”搜索“匹配”的基本表单。这只是一个概念证明,因为我仍在学习。

这是我的模型:

class OmMatch < ActiveRecord::Base
end

这是我的控制器:

class OmMatchesController < ApplicationController

 def search
  @search = OmMatch.search(params[:search])
  @match = @search.all
 end 
end

这是视图:

<html> 
  <head><title>"Matches"</title></head>
  <body>
    <% form_for @search do |f| %>
    <p>
      <%= f.label :country_equals, "Country" %><br />
      <%= f.text_field :country_equals %>
    </p>

    <p>
      <%= f.submit "Submit" %>
    </p>

  <% end %>

  <table>
  <tr>
    <th>"Match Name"</th>
    <th>"Country"</th>
  </tr>
  <% @match.each do |match| %>
  <tr>
    <td><%=h match.matchname %></td>
    <td><%=h match.country %></td>
  </tr>
 <% end %>
 <table>
</body>
</html>

我认为问题出在搜索未初始化,但我不知道该怎么做。

【问题讨论】:

    标签: ruby-on-rails searchlogic form-for


    【解决方案1】:

    当你这样做时

    <% form_for @search do |f| %>
    

    它期望@search 是一个初始化的活动记录对象,其路由定义在 routes.rb 文件中。

    我假设您遇到的问题是在对 OmMatch 搜索操作执行 GET 请求时。

    如果搜索是一个可以初始化的对象,那么只需添加

    @search = Search.new
    

    到你的控制器。

    您需要考虑这里的工作流程,了解当通过链接请求表单时运行什么操作,以及当用户发布表单时会发生什么。

    记住你可以运行

    rake routes
    

    查看您的应用程序知道的资源和控制器的所有路由。

    我建议您查看 railscasts 的屏幕截图,尤其是关于路由的那些。了解控制器代码如何通过 url 映射非常重要。 http://railscasts.com/episodes?search=routing 正确映射路由并了解何时调用每个操作后,就可以确保在需要对象之前创建对象。

    【讨论】:

    • 抱歉,过了几天。我现在正在解决这个问题,但我仍在苦苦挣扎。我将 map.connect ':controller/:action/' 添加到我的 routes.rb 文件中,以便我可以浏览到 om_matches/search。我还在 OmMatchesController 的搜索操作中添加了行 @search = Search.new。我现在收到以下错误 uninitialized constant OmMatchesController::Search 我现在很困惑。您需要在控制器中的操作之外声明变量还是制作新模型或其他东西?
    • 我在答案末尾添加了一些信息,如果您需要更多帮助,请发布您正在访问的 URL 以及有关您的路由和控制器操作的更多信息。
    猜你喜欢
    • 1970-01-01
    • 2018-02-12
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多