1
class User
    has_many :posts do
      def latest(report_date)
        order(:report_date).where('report_date <= ?', report_date).limit(1)
      end
    end
end

class Post
    belongs_to :user
end

我想用每个用户的最后一篇文章检索用户的记录。

我可以这样做:

users = User.all.map{|user| user.posts.latest(7.weeks.ago).first}.compact

有没有更好的方法来写这个?就像是:

users = User.posts.latest(7.weeks.ago).all

如果那是有效的?

4

1 回答 1

2

I tend to add something like this. Would it work in your case? It's nice because you can 'include' it in list queries...

class User < ActiveRecord::Base
  has_many :posts
  has_one :latest_post, :class_name => 'Post', :order => 'report_date desc'

  ...

end

In practice, you would do something like this in the controller:

@users = User.include(:latest_post)

And then, in the view where you render the user, you could refer to user.lastest_post and it will be eager loaded.

For example - if this was in index.html.haml

= render @users

you can access latest_post in _user.html.haml

= user.name
= user.latest_post.report_date
于 2013-05-11T01:51:48.300 回答