【问题标题】:Is it possible to look beyond self in self.posts.find?是否可以在 self.posts.find 中超越自我?
【发布时间】:2009-05-23 23:23:45
【问题描述】:

在下面的recent_posts_on_self 上展开,我想添加一个all_recent_posts_on_self 方法,但我不确定是否可以使用语法self.posts.find。另一方面,all_recent_posts_on_class 似乎很简单。

class User < ActiveRecord::Base
  has_many :posts, :class_name => "Post" , :foreign_key => "author_id"
  has_many :comments, :class_name => "Comment", :foreign_key => "author_id"

  def recent_posts_on_class
    Post.find(  :all, :conditions => ['author_id = ?', self.id],
                :order => 'created_at asc', :limit => 5)
  end

  def recent_posts_on_self
    self.posts.find(:all, :order => 'created_at ASC', :limit => 5)
  end
end

在上面的示例中,我有两种方法可以找到与用户关联的最近的博客文章。我可以调用 Post.find 并将 author_id 传递给它,或者我可以调用 self.posts.find 而我不需要传递作者 ID。我认为这是因为在后一种情况下,self.posts 已经根据用户对象的主键和与该用户关联的 has_many :posts 进行了限制。在这种情况下这是一个优势,因为我不需要麻烦地将 author_id 作为参数传递。但是,如果我不需要按作者限制查询,是否可以创建一个 all_recent_posts_on_self 来执行此操作?

我说的是这个方法的等价物(省略了:conditions):

  def all_recent_posts_on_class
    Post.find(:all, :order => 'created_at asc', :limit => 5)
  end

但使用 self.posts.find 而不是 Post.find

  def all_recent_posts_on_self
    self.posts.find(...)
  end

还有:

即使可以使用 self.posts.find 来做到这一点,使用 Post.find 是否“更好”?

【问题讨论】:

    标签: ruby-on-rails model find self


    【解决方案1】:

    这并不完全是您所要求的,但我认为这有助于了解并遵循常见模式有助于避免复杂或令人困惑的实现。

    执行此操作的“Rails 方式”是使用命名范围:

    class Post < ActiveRecord::Base
      belongs_to :user
      named_scope :recent, :order => 'created_at desc', :limit => 5
    end
    
    class User < ActiveRecord::Base
      has_many :posts
    end
    

    没有比这更具声明性和易于阅读的了:

    user.posts.recent # 5 most recent posts by the user
    Post.recent # 5 most recent posts globally
    

    【讨论】:

    • 那真是太好了。不知道你能做到这一点。谢谢。
    【解决方案2】:

    我不确定您为什么要使用 self.posts.find(..) 来查找其他作者的帖子。此成语专门用于查找与特定实例关联的对象的子集。

    Post.find() 是当您不想限制特定用户模型时应该使用的。毕竟,User 对象上的 posts() 方法只是一种便利,它实际上与对 Post.find(:all, :conditions => ['author_id', self.id]) 的(缓存)调用相同。

    【讨论】:

    • 好的,我接受你关于为什么使用 Post.find() 来查找其他作者的帖子的逻辑。但是,通过 self.posts.find() 查找其他作者的帖子甚至 可能 吗?
    • 不可能。您所做的任何事情都会将查询段组合在一起。所以你会有“AND author_id = 5 AND author_id = 6”。除非您使用的是我从未听说过的 RDMS,否则这不太可能给您任何帮助。 :)
    猜你喜欢
    • 2017-12-28
    • 2015-05-03
    • 1970-01-01
    • 2011-05-21
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    相关资源
    最近更新 更多