按关联 AR 对象的属性值选择活动记录对象



给定一个与另一个ActiveRecord类(例如标签)关联的ActiveRecord类(例如帖子),我如何仅选择那些与具有特定属性值的标签关联的帖子(例如 Tag.name="音乐")。

到目前为止,我在帖子上定义了一个类方法,如下所示:

def self.tag_filter(tag_name, posts)
  unless tag_name == '' || posts == nil
    postlist = posts
    posts = []
    postlist.all.each do |post|
      post.tags.each do |tag|
        if tag.name == tag_name 
          posts<<post
        end
      end
    end
  end
  posts
end

要在控制器中像这样使用它:

def posts_filter
  @user = current_user
  @posts = @user.posts
  tag_filtered_posts = Post.tag_filter(params[:tag_select], @posts)
  ..
end

但这从一开始就感觉不对,不知何故,我觉得这应该更容易实现。我错过了什么?

您可以使用连接方法:

Post.joins(:tags).where(tags: { name: tag_name })

最新更新