简体   繁体   English

如何构建同时返回用户帖子和帖子类别的查询?

[英]How to structure a query returning both a user's posts and the posts' categories?

In my controller's index action: 在我的控制器的index操作中:

@posts = current_user.posts.process_and_return_posts  

In the model: 在模型中:

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

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

In the view I will display the posts by category, I wonder how I should structure the query and in what type of collection I want the posts? 在视图中,我将按类别显示帖子,我想知道如何构造查询以及我想要哪种类型的帖子?

I need the collection to contain both the Category objects and the Post objects (as I will order them when iterating over them in the view). 我需要集合同时包含Category对象和Post对象(因为在视图中对其进行迭代时将对其进行排序)。

I guess what you want is 我想你想要的是

group_by { |post| post.category }

This way you can use in your view 这样您可以在视图中使用

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

This should also work in combination with your association 这也应该与您的协会一起工作

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

It's important to notice that current_user.posts actually returns Array object filled with Post objects, and not a post object. 重要的是要注意current_user.posts实际上返回的是用Post对象填充的Array对象,而不是 post对象。

So you should monkey patch process_and_return_posts method in Enumerable module instead of Post class. 因此,您应该在Enumerable模块(而不是Post类)中使用猴子补丁process_and_return_posts方法。

You can monkey patch in many ways on Rails, but my favorite way is to put all the monkey patched code in one place, so that I know what's been monkey patched before. 您可以在Rails上以多种方式进行猴子补丁,但是我最喜欢的方法是将所有猴子补丁代码放在一个地方,这样我就知道以前猴子补丁了。

From your rails directory, inside config/initializers , create a directory called extensions . 在您的rails目录中的config/initializers内部,创建一个名为extensions的目录。 This is where you can put all your monkey patched code. 您可以在这里放置所有猴子修补的代码。 Inside config/initializers/extensions , create a Ruby file called, enumerables.rb so that you know later that this code contains code for enumerables. config/initializers/extensions内部,创建一个名为enumerables.rb的Ruby文件,以便稍后您知道此代码包含可枚举的代码。

In config/initializers/extensions/enumerables.rb , config/initializers/extensions/enumerables.rb

module Enumerable
  def process_and_return_posts
    # your code here.
  end
end

Be sure to restart your rails server, whenever you update anything in initializers . 每当您在initializers更新任何内容时,请确保重新启动Rails服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM