【问题标题】:How to define scope to get one record of a has_many association?如何定义范围以获取 has_many 关联的一条记录?
【发布时间】:2013-05-05 17:23:07
【问题描述】:
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

如果那是有效的?

【问题讨论】:

    标签: ruby-on-rails scope has-many


    【解决方案1】:

    我倾向于添加这样的内容。它适用于你的情况吗?这很好,因为您可以在列表查询中“包含”它...

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

    实际上,您会在控制器中执行以下操作:

    @users = User.include(:latest_post)
    

    然后,在您呈现用户的视图中,您可以引用 user.lastest_post ,它将被预先加载。

    例如 - 如果这是在 index.html.haml 中

    = render @users
    

    你可以在_user.html.haml中访问latest_post

    = user.name
    = user.latest_post.report_date
    

    【讨论】:

    • 不幸的是,has_one 关系不适用于 ActiveRecord。 #<0x2e231dff>
    猜你喜欢
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 2020-07-13
    • 2022-12-18
    • 2017-05-21
    相关资源
    最近更新 更多