【问题标题】:Has_and_belong_to_many associationHas_and_belong_to_many 关联
【发布时间】:2021-04-02 07:13:05
【问题描述】:

我有两个模型,它们之间没有关联。所以,我生成了一个迁移并添加了一个关联。

class Post < ActiveRecord::Base
  has_and_belongs_to_many :workspaces
end
class Workspace < ActiveRecord::Base
  has_and_belongs_to_many :posts
end
class CreateJoinTablePostsUsers < ActiveRecord::Migration
  def change
    create_join_table :posts, :workspaces do |t|
      # t.index [:post_id, :workspace_id]
      # t.index [:workspace_id, :post_id]
    end
  end
end

我目前有一个显示所有帖子的页面。但是,我在帖子创建表单中添加了一个多选,以便在创建时选择一个或多个工作区。我希望能够仅显示为该特定工作区创建的帖子,而不是所有帖子,就像目前一样。 我的控制器如下:

class PostsController < Admin::BaseControlle
  def index
    respond_to do |format|
      format.html
      format.json do
        @posts = Post.all.order(:order)
        render json: present_collection(@posts, PostPresenter).map(&:as_json)
      end
    end
  end

  private

  def post_params
    params.require(:post).permit(:label, :url, :active, workspace_ids: [])
  end
end

我可以通过这种方式获得相关的工作区:

Post.first.workspaces

但我想显示所有帖子,但在尝试此命令时出现错误:

Post.all.workspaces

如何更改我的控制器并完成它?提前感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails controller has-and-belongs-to-many model-associations


    【解决方案1】:

    嗯,你应该有一个 table 按照 Rails 约定称为 PostsWorkspaces,所以你应该能够执行以下操作:

    posts_in_workspaces = PostsWorkspaces.all.pluck(:post_id)
    Posts.where(id: posts_in_workspaces )
    

    上面将返回至少有一个workspace 关联的postsPost.all.workspaces 方法的问题在于并非所有帖子都需要关联一个工作区(或多个),您也可以想想Post.all 就像select * from posts 这不是你想要完成的。

    希望以上内容有所帮助! ?

    【讨论】:

    • 如果你使用select 而不是pluck,Rails 将在 sql 中使用子查询,从而提高性能。
    • 是的,这是一个改进?
    • 乐于助人! ?
    【解决方案2】:

    你想错了。 Post.first.workspaces 有效,因为关联应用于返回的Post 实例。但是Post.all 返回一个集合。

    最好的办法是执行以下操作。

    # Return all posts that have a workspace associated
    posts = Post.joins(:workspaces).all.distinct
    
    posts.each do |post|
     post.workspaces
    end
    

    如果您想在没有工作区的情况下包含帖子

    posts = Post.includes(:workspaces).all
    
    posts.each do |post|
     post.workspaces
    end
    

    【讨论】:

      猜你喜欢
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-11
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 2010-10-06
      相关资源
      最近更新 更多