2013-01-13 41 views
0

我在Ruby on Rails中制作了一个社交网络应用程序,当我在Micropost模型中使用where方法内部和类方法时,我看到了一个有趣的行为,工作没有在它前面指定的类(像“Micropost.where()”)Rails,其中类方法中的功能vs实例方法中的功能

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 

然后,如果我使用“其中”,而不是“User.where”然后我会得到这样的错误:

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

这是为什么发生? friends()方法中的where方法是否认为我将它用作当前对象(self.friends())上的实例方法?

回答

3

是的。在实例方法中,where正在发送给用户对象;然而,只有用户类别知道如何响应where

0

在Ruby方法调用总是发送到当前self。 您甚至可以在您的方法中打印self并查看它将显示的内容。

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

在您的friends()方法中,self无法识别消息'where'(在Ruby中调用方法实际上意味着将消息发送给对象)。