0

我正在使用 Ruby on Rails 制作社交网络应用程序,当我使用内部的 where 方法和 Micropost 模型中的类方法时,我看到了一个有趣的行为,它无需指定前面的类即可工作(例如“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())的实例方法?

4

2 回答 2

3

是的。在实例方法内部,where正在发送给 User 对象;但是,只有 User知道如何响应where.

于 2013-01-13T18:47:11.763 回答
0

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

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

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

于 2013-01-15T01:57:34.893 回答