Rails has_many 通过创建关系记录

Rails has_many through creating record with relationship

我有一个 "posts" 模型、一个 "teams" 模型和一个 "post_memberships" 模型。我希望 "posts" 与许多 "teams" 相关,并且 "teams" 与许多 "posts" 相关。我已经正确设置了所有内容(我认为),但我不确定如何创建一个包含多个相关团队的 "post" 记录。

    class Post < ApplicationRecord

        has_many :post_memberships
        has_many :teams,through: :post_memberships
    end

    class Team < ApplicationRecord

    has_many :post_memberships
    has_many :posts,through: :post_memberships

end

    class PostMembership < ApplicationRecord

    belongs_to :team
    belongs_to :post

end

我的 "post" 表单将 team_id 的多个 select 字段发送到 posts_controller 中的创建操作:

    def create
        @post = Post.new(post_params)
        if post_params[:teams]
          post_params[:teams].each do |id|

            @post.teams << Team.find(id)

          end
        end

        respond_to do |format|
          if @post.save
            format.html { redirect_to @post, notice: 'Post was successfully created.' }
            format.json { render :show, status: :created, location: @post }
          else
            format.html { render :new }
            format.json { render json: @post.errors, status: :unprocessable_entity }
          end
        end
      end

def post_params
      params.require(:post).permit(:title, :body, :teams)
    end

我似乎无法用 "PostMembership" 创建 "Post"。

using arrays in strong parameters 中有一个注意事项,因此您需要更改 post_params 方法:

def post_params
  params.require(:post).permit(:title, :body, teams: [])
end

但这还没有完全结束,因为现在您的 Post.new 收到团队协会的一组 ID,应该会抛出 AssociationTypeMismatch。所以我们需要稍微改变一下你的创建方法:

def create
  @post = Post.new(post_params.except(:teams))
  # ...

其他一切看起来都应该正常工作:)