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".