RAILS HABTM复选框不会更新

时间:2013-10-23 17:02:50

标签: ruby-on-rails checkbox has-and-belongs-to-many

我正在尝试按照本教程实现HABTM复选框: http://www.justinball.com/2008/07/03/checkbox-list-in-ruby-on-rails-using-habtm/

虽然一切似乎都运行良好,但更新不会保存到我的数据库中。 我的控制器如下所示:

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

我的_form.html.erb是这样的:

<%= 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 %>

所以我做了教程中的所有操作,:名称保存没有任何问题,但是id不会保存到数据库中。没有错误消息。有没有人知道可能出现什么问题?也许在某个地方有一些遗失的许可?

1 个答案:

答案 0 :(得分:0)

所以最后我找到了解决这个问题的方法。 我通过在def update中添加以下行来强制更新project_ids:

    @userrole.project_ids=params[:userrole][:project_ids]