2014-12-08 28 views
0

我正在创建一个用户ACL我有2个模型之一是users_group和另一个是access_sections。 现在让我们supouse我有2个access_sections(页,用户) 我想这两个access_sectionsusers_group, 现在这里是我已经做了 我创建多对多关联关联,增加了新的连接表access_sections_user_groups 每当我添加新用户我通过实例变量来获取所有可用的access_sections,我将它们显示为新用户组表单中的复选框,一旦我检查了访问部分I中的任何一个,并在数组中插入所有元素,并在 id和编号一切正在工作现在我想这样做,当我编辑用户组我的复选框应该检查,如果具体access_sections与用户组关联如何标记为Rails 4中的关联值检查框与多对多关联

user_group_controller.rb

def create 
@user_group = UserGroup.new(group_params) 


if @user_group.save 
    flash[:notice] = "User group added !" 
    flash[:type] = "success" 

    if params[:user_group][:access_sections].present? 
    params[:user_group][:access_sections].each do |f| 
     UserGroup.find(@user_group.id).access_sections << AccessSection.find(f) 
    end 
    end 
    redirect_to(:action => "index") 
else 
    flash[:notice] = "error while adding new group!" 
    flash[:type] = "danger" 
    render("add_new") 
end 
end 

USER_GROUP/_form.html.erb

<%= f.label("Add section to Access Control ") %> 

<% @acl_sections.each do |k| %> 
    <%= f.check_box(:access_sections, { :multiple => true }, k.id, nil) %> 
<% end %> 

回答

0

应工作

f.check_box(:access_section_ids, { :multiple => true }, k.id, nil) 

因此,你需要更新你的模型像这样:

def create 
    if @user_group.create(user_group_params) 
    # ... 
    end 
end 

def user_group_params 
    params.require(:user_group).permit(access_section_ids: []) 
end 
+0

非常感谢@amenzhinsky对我的作品。 – 2014-12-08 15:23:02