Reputation: 449
I have a "posts" model, a "teams" model, and a "post_memberships" model. I want "posts" to be related to many "teams" and "teams" to be related to many "posts". I have everything set up properly (i think), but I am unsure of how to create a "post" record with multiple teams related to it.
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
My "post" form sends a multiple select field of team_id's to the create action in the 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
I cannot seem to create a "Post" with a "PostMembership".
Upvotes: 1
Views: 435
Reputation: 1311
There is a caveat in using arrays in strong parameters, so you need to change your post_params method:
def post_params
params.require(:post).permit(:title, :body, teams: [])
end
That's not quite the end of it though, because now your Post.new receives an array of ids for the teams association, which should throw AssociationTypeMismatch
. So we need to change your create method a tiny little bit:
def create
@post = Post.new(post_params.except(:teams))
# ...
everything else looks like it should be working :)
Upvotes: 1