【问题标题】:Undefined method in Rails 4Rails 4 中的未定义方法
【发布时间】:2015-04-21 01:02:57
【问题描述】:
Ruby version 2.15
Rails version 4.2.15

在我的 app/views/organizations/index.html.erb 中,我有:

<table class="table table-striped">
  <thead>
  <tr>
    <th><%= sortable "org_name", "Organization" %></th>
    <th><%= sortable "city", "City" %></th>
    <th colspan="3"></th>
  </tr>
  </thead>  

在我的 app/controllers/organizations_controller.rb 中,我有以下内容:

include ApplicationHelper
helper_method :sort_column, :sort_direction  

private
  def sort_direction
    %w[asc desc].include?(params[:sort_direction]) ?  params[:sort_direction] : "asc"
  end
  def sort_column
    Organization.column_names.include?(params[:sort_order]) ? params[:sort_order] : "org_name"
  end   

在我的 app/helpers/application_helper.rb 中,我有以下内容:

  def sortable(column, title = nil)
    title ||= column.titleize
    direction = (column == params[:sort_order] && params[:sort_direction] == "asc") ? "desc" : "asc"
    link_to title, :sort_order => column, :sort_direction => direction
  end

当我单击列标题(组织)时,我收到一条错误消息:

undefined method 'sortable'

它指向app/views/index.html.erb

我做错了什么?

澄清:

如果我将 sortable 方法放在 organizations_helper.rb 中,这会很好,但是将它放在 application_helper.rb 中的目的是它也可以用于其他模型(我有几个其他模型可以使用这个功能)

【问题讨论】:

  • 我相信你应该在操作之前做 :sort_column 和 :sort_direction 而不是应用控制器中的辅助方法
  • 点到是什么意思?它说错误发生在哪一行?
  • 它出现在 app/views/organizations/index.html.erb 中调用 sortable 的第一行

标签: ruby-on-rails


【解决方案1】:

organizations_controller.rb 中,将 include ApplicationHelper 替换为 add_template_helper(ApplicationHelper) 以使其在您的模板中可用。

【讨论】:

  • 好的,我将您的实际代码放在一个(否则)空的 Rails 应用程序中,它运行良好(我将 root 路由到 organizations#index)。我想知道您的环境中是否有其他东西在干扰。
  • 可能。我以前使用过这段代码,效果很好。如果我把它放在组织助手中,它就可以工作。这就是为什么我有点不解
猜你喜欢
  • 2015-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-24
  • 2013-07-16
相关资源
最近更新 更多