我正在使用 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())的实例方法?