【问题标题】:Ruby On Rails ActiveRecord select stuff with WHERE conditionRuby On Rails ActiveRecord 选择具有 WHERE 条件的内容
【发布时间】:2016-02-07 12:11:36
【问题描述】:

我的应用程序中有PostUser 实体。

他们有相应的belongs_tohas_many 关系。我使用gem devise作为用户授权/认证系统。

如果Postuser_id 并且它与current_user.id 相同,则这段代码选择所有帖子,并将其分配给实例变量:

@post = Post.where(:user_id => current_user.id)

问题是:

如何选择用户创建的最新帖子(我想我会使用.last 方法来实现)

但问题是我不知道如何在我的实例变量内的一个查询中使用.where.last

【问题讨论】:

    标签: ruby-on-rails ruby activerecord devise


    【解决方案1】:

    ActiveRecord where 方法返回一个 ActiveRecord 关系对象。这意味着可以将其他 AR 方法链接到它上面。有几种方法可以做到这一点。

    @post = Post.where(user: current_user)
    

    请注意,您可以在不指定 id 的情况下传递 where 对象。例如,where(user: current_user)where(user_id: current_user.id) 相对。 AR 会弄清楚你想要做什么。

    你也可以通过用户。

    @post = current_user.posts.last
    

    但请注意,last 不一定能满足您的需求。它默认使用对象id。这意味着最近更新的帖子可能不会优先。如果您使用软删除,这也可能是一个问题。您可能希望将created_atupdated_at 显式添加到条件中。

    @post = current_user.posts.order(created_at: :desc).last
    

    您可能希望将其包装在范围内。

    class Post
      scope :most_recent, -> { order(created_at: :desc).last }
    end
    @post = current_user.posts.most_recent
    

    【讨论】:

      【解决方案2】:

      您可以对用户创建的帖子按升序或降序排序,要获得用户最新的帖子,您可以按降序排序。

      在您的帖子模型中可以将范围定义为最近的

      scope :recent,  -> { order(created_at: :desc) }
      
      @post = current_user.posts.recent.first
      

      【讨论】:

        【解决方案3】:

        我的问题已经解决了。

        这对我来说就像一个魅力:

        @post = Post.joins(:user).where(posts: { user_id: current_user.id }).last
        

        【讨论】:

        • 这不是解决这个问题的好方法。你正在做一个不必要的加入。
        • 是的,稍后会进行重构。感谢您的回答!
        猜你喜欢
        • 1970-01-01
        • 2022-06-10
        • 1970-01-01
        • 2021-12-09
        • 2018-06-30
        • 2015-09-13
        • 1970-01-01
        • 1970-01-01
        • 2010-10-14
        相关资源
        最近更新 更多