【问题标题】:Rails, where function in class methods vs where function in instance methodsRails,类方法中的函数与实例方法中的函数
【发布时间】:2013-01-13 18:42:59
【问题描述】:

我正在使用 Ruby on Rails 制作一个社交网络应用程序,当我使用内部的 where 方法和 Micropost 模型中的 class 方法时,我看到了一个有趣的行为,它可以在不指定前面的类的情况下工作(类似于“ Micropost.where()")

    class Micropost < ActiveRecord::Base
      attr_accessible :content
      belongs_to :user

      validates :user_id, presence: true
      validates :content, presence: true, length: { maximum: 255 }

      default_scope order: "microposts.created_at DESC"

      def self.from_users_followed_by(user)
        followed_user_ids = "SELECT followed_id FROM relationships
                             WHERE follower_id = :user_id"
        where("user_id IN (#{followed_user_ids}) OR user_id = :user_id", 
               user_id: user.id )
      end  
    end

但是当我在下面这样的实例方法中使用它时,它需要知道模型的名称。

    class User < ActiveRecord::Base
      ...
      ...
      def friends()
        sql_direct_friends   = "SELECT friend_id FROM friendships
                                WHERE approved = :true_value AND user_id = :user_id"
        sql_indirect_friends = "SELECT user_id FROM friendships
                                WHERE approved = :true_value AND friend_id = :user_id"                       
        User.where("id IN (#{sql_direct_friends}) OR id IN (#{sql_indirect_friends})", user_id: id, true_value: true)
      end  
    end

那么如果我使用“where”而不是“User.where”,那么我会收到如下错误:

  NoMethodError: undefined method `where' for #<User:0x00000004b908f8>

为什么会这样? Friends() 方法中的 where 方法是否认为我将其用作当前对象(self.friends())的实例方法?

【问题讨论】:

    标签: ruby activerecord ruby-on-rails-3.2


    【解决方案1】:

    是的。在实例方法内部,where 被发送到 User 对象;然而,只有用户知道如何回复where

    【讨论】:

      【解决方案2】:

      在 Ruby 中方法调用总是发送到当前的self。 你甚至可以在你的方法中打印self,看看它会显示什么。

      self 将是def self.from_users_followed_by 中的一个类,并且将是def friends 中的一个类的实例。

      毫无疑问,friends() 方法中的 self 无法识别消息“在哪里”(在 Ruby 中调用方法实际上意味着向对象发送消息)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-14
        • 1970-01-01
        • 2020-02-03
        • 2012-07-11
        • 2013-11-25
        • 2015-10-02
        • 1970-01-01
        相关资源
        最近更新 更多