【问题标题】:How to structure a query returning both a user's posts and the posts' categories?如何构造一个返回用户帖子和帖子类别的查询?
【发布时间】:2014-04-24 18:55:25
【问题描述】:

在我的控制器的索引操作中:

@posts = current_user.posts.process_and_return_posts  

在模型中:

class Post < ActiveRecord::Base
  belongs_to :user
  belongs_to :category

  def self.process_and_return_posts
    # doing some cleanup
    # return posts
  end
end

在我将按类别显示帖子的视图中,我想知道我应该如何构建查询以及我想要帖子在什么类型的集合中?

我需要集合同时包含 Category 对象和 Post 对象(因为我会在视图中迭代它们时对它们进行排序)。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    我猜你想要的是什么

    group_by { |post| post.category }
    

    这样你就可以在你的视图中使用

    Post.process_and_return_posts.keys.each do |category|
      category.posts ...
    end
    

    这也应该与您的关联一起使用

    current_user.posts.process_and_return_posts.keys.each do |category|
      category.posts ...
    end
    

    【讨论】:

      【解决方案2】:

      请务必注意,current_user.posts 实际上返回的是用 Post 对象填充的 Array 对象,而不是一个 post 对象。

      所以你应该在 Enumerable 模块而不是 Post 类中修补 process_and_return_posts 方法。

      您可以在 Rails 上通过多种方式进行猴子补丁,但我最喜欢的方式是将所有猴子补丁的代码放在一个地方,这样我就可以知道之前猴子补丁的内容。

      在您的 rails 目录中,在 config/initializers 内,创建一个名为 extensions 的目录。这是您可以放置​​所有猴子补丁代码的地方。在 config/initializers/extensions 中,创建一个名为 enumerables.rb 的 Ruby 文件,以便稍后知道此代码包含可枚举代码。

      config/initializers/extensions/enumerables.rb

      module Enumerable
        def process_and_return_posts
          # your code here.
        end
      end
      

      每当您更新 initializers 中的任何内容时,请务必重新启动您的 Rails 服务器。

      【讨论】:

        猜你喜欢
        • 2019-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-13
        • 1970-01-01
        • 1970-01-01
        • 2015-04-19
        • 2017-04-03
        相关资源
        最近更新 更多