Skip to content

Instantly share code, notes, and snippets.

@DanKnox
Created November 11, 2012 00:35
Show Gist options
  • Save DanKnox/4053162 to your computer and use it in GitHub Desktop.
Save DanKnox/4053162 to your computer and use it in GitHub Desktop.
Mass assignment error with has_and_belongs_to_many
# Option 1
# Explicitly assign it to avoid the mass assignment error.
def create
user_ids = params[:project].delete(:user_ids)
@project = Project.new(params[:project])
@project.user_ids = user_ids
if @project.save
flash[:success] = "Project successfully created"
redirect_to project_overview_url(@project.slug)
else
@users = User.all
render :new
end
end
# Option 2
# Disable mass assignment protection for this save only.
def create
@project = Project.new(params[:project], :without_protection => true)
if @project.save
flash[:success] = "Project successfully created"
redirect_to project_overview_url(@project.slug)
else
@users = User.all
render :new
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment