在application_helper.rb中调用User上的方法将返回未定义的方法

时间:2013-08-09 21:25:24

标签: ruby-on-rails

我正在尝试编写一个帮助方法,将浮点数从英制转换为公制。我在application_helper.rb中有以下方法:

  module ApplicationHelper
    def weight_conversion_factor
      if User.measurement_units == 'metric'
        0.453592
      elsif User.measurement_units == 'imperial'
        1
      end
    end
  end

如果我在视图中调用current_user.measurement_units,则效果很好。当我尝试在application_helper.rb文件中调用User.measurement_units时,我为#`

获得了undefined method measurement_units'

我在这里缺少什么?我不应该只能在applicatoin_helper中拨打用户measurement_units吗? measurement_units是User表中的一个字段。

谢谢!

2 个答案:

答案 0 :(得分:2)

User是类,而不是实例。在辅助方法中也使用current_user

module ApplicationHelper
  def weight_conversion_factor
    return nil if current_user.nil?

    if current_user.measurement_units == 'metric'
      0.453592
    elsif current_user.measurement_units == 'imperial'
      1
    end
  end
end

或者,这可以放在User模型中:

class User < ActiveRecord::Base

  # Other code...

  def weight_conversion_factor
    if measurement_units == 'metric'
      0.453592
    elsif measurement_units == 'imperial'
      1
    else
      nil
    end
  end

end

答案 1 :(得分:1)

如果measurement_units是“用户”表中的字段,则需要说明要访问的字段的特定用户(实例)。例如,您可以执行其中任何操作,因为它们访问特定用户的measurement_units:

current_user.measurement_units
User.new.measurement_units
User.last.measurement_units
User.find(1).measurement_units

如果您希望能够访问用户()上的测量单位,您可以在User.rb模型中定义:

def self.measurement_units
  ...
end

通过此操作,您可以无错误地运行:User.measurement_units

在您的情况下,您只需在帮助程序中运行current_user.measurement_units