我有一个"帖子"模特,"团队"模特和" post_memberships"模型。我想"帖子"与许多"团队有关"和#34;团队"与许多"职位相关"。我已经正确设置了所有设置(我认为),但我不确定如何创建一个"帖子"与多个与之相关的团队进行记录。
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
我的&#34;帖子&#34; form将posts_id的多个select字段发送到posts_controller中的create动作:
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
我似乎无法创建一个&#34; Post&#34;使用&#34; PostMembership&#34;。
答案 0 :(得分:1)
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))
# ...
其他一切看起来应该有效:)