【问题标题】:Why does my new class method in a Rails model result in nil?为什么我在 Rails 模型中的新类方法结果为零?
【发布时间】:2014-11-09 14:59:10
【问题描述】:

我刚刚开始学习 Rails。我有一个测试项目,我用一些现有的示例数据向 Post 模型类添加了一个实例方法和一个类方法。

class Post < ActiveRecord::Base
  has_many :comments

  attr_accessor :region

  def sport
    puts "Football"
  end

  def self.region
    puts "West"
  end
end

当我运行 Post.first.sport 时,我正确地得到了“足球”

但是当我运行 Post.first.region 时我得到了 nil。为什么 Rails 控制台不返回“West”?

谢谢!

【问题讨论】:

  • 因为 Post.first 返回的 Post 实例没有 #region 实例方法。

标签: ruby-on-rails ruby class activerecord model


【解决方案1】:

由于self.region 被定义为类方法,您应该运行Post.region 以输出“West”

请参阅https://stackoverflow.com/a/11655868/1693764 以获得对类与实例方法的详细描述

【讨论】:

    【解决方案2】:

    失败是因为您在实例对象上使用了类方法。
    做:

    Post.region #=> 'west'
    

    当您添加“自我”时。对于一个方法,它变成一个类方法。类方法在整个类上调用。另一方面,实例方法是在类的实例上调用的。

    当您需要适用于整个类的方法时,请使用类方法。例如像 find_post_with_most_cmets 这样的方法。

    Post.find_post_with_most_comments
    

    在处理类的特定实例时使用实例方法。例如 first_comment 之类的方法

     @post = Post.find(params[:post_id])
     @post.first_comment
    

    【讨论】:

      【解决方案3】:

      attr_accessor 为类添加实例方法。

      根据您的代码,它在初始化 Post 对象期间在 getter 方法中创建一个名为“@region”的实例变量。

      def region
        @region
      end
      

      实例变量的默认值为'nil'。所以当你访问 Post.first.region 时,它会返回实例变量的默认值。

      在'self.region'代码中,它被定义为类方法。所以可以使用'Model.class_method'语法调用它

      因此在类对象上调用类方法,而在实例对象上调用实例方法。

      更深入地了解 ruby​​ 元类以获得全貌,它将让您对 ruby​​ 架构更加好奇,并帮助您了解更多。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-26
        • 1970-01-01
        相关资源
        最近更新 更多