I am trying to realize HABTM checkboxes following this tutorial: http://www.justinball.com/2008/07/03/checkbox-list-in-ruby-on-rails-using-habtm/
While everything seems to work nicely the updates are not saved to my database. My controller looks like the following:
class UserrolesController < ApplicationController
before_action :set_userrole
def edit
@projects=Project.all
end
def update
params[:userrole][:project_ids] ||= []
@userrole = Userrole.find(params[:id])
if @userrole.update_attributes(userrole_params)
flash[:notice] = "Settings have been saved."
redirect_to edit_userrole_url(@userrole)
else
flash.now[:error] = @userrole.errors
setup_form_values
respond_to do |format|
format.html { render :action => :edit}
end
end
end
private
def set_userrole
@userrole = Userrole.find(params[:id])
end
def userrole_params
params.require(:userrole).permit(:name, :project_ids)
end
end
My _form.html.erb like this:
<%= form_for(@userrole) do |f| %>
<% if @userrole.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@userrole.errors.count, "error") %> prohibited this person from being saved:</h2>
<ul>
<% @userrole.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="center">
<div class="field">
<%= f.label :Name %>
<%= f.text_field :name %>
</div>
<ul class="checkbox-list">
<% @projects.each do |project| -%>
<li><%= check_box_tag "userrole[project_ids][]", project.id, userrole_edits_project?(project) -%> <%= project.name -%></li>
<% end -%>
</ul>
<div class="actions">
<%= f.submit "Speichern", class: "btn btn-primary" %>
</div>
</div>
<% end %>
So I did everything like in the tutorial, the :name is saved without any problems, but the ids are not saved to the database. There is no error message. Does anybody has an idea what might go wrong? Maybe some missing permission somewhere?
So finally I found a work around for this problem. I forced the update of project_ids by adding the following line in def update:
@userrole.project_ids=params[:userrole][:project_ids]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.