我有一个复杂的模型关联:
class Company < ActiveRecord::Base
has_many :roles, :dependent => :destroy
has_many :users, :through => :roles
end
class Role < ActiveRecord::Base
belongs_to :user
belongs_to :company
attr_accessor :roles_attributes
attr_accessible :roles_attributes, :active, :company_id, :role
validates_presence_of :company_id, :role
validates_uniqueness_of :user_id, :scope => :company_id, :message => "Users may only have one role per company."
end
class User < ActiveRecord::Base
has_many :roles, :dependent => :destroy
accepts_nested_attributes_for :roles, :allow_destroy => true
has_many :companies, :through => :roles
end
这里的意图是单个用户(电子邮件地址)可以在不同的公司下登录,每个公司具有不同的权限(角色)。
我有用户嵌套在公司下,我的更新控制器工作正常,但现在我似乎无法让新/创建控制器工作:
控制器:
def new
@user = User.new
@role = @user.roles.build.company_id = session[:company_id]
respond_to do |format|
format.html # new.html.erb
format.json { render json: @user }
end
end
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render json: @user, status: :created, location: @user }
else
format.html { render action: "new" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
和视图:
<%= simple_nested_form_for [:company, @user] do |f| %>
<fieldset>
<div class="form-horizontal">
<%= f.input :email %>
<%= f.input :name_first %>
<%= f.input :name_last %>
<%= f.input :title %>
<%= f.input :phone %>
<%= f.input :mobile %>
<%= f.simple_fields_for :roles, @role do |role_form| %>
<%= role_form.hidden_field :company_id %>
<%= role_form.input :active %>
<%= role_form.input :role, :collection => [ "Guest", "User", "Inspector", "Owner"] %></td>
<% end %>
<%= f.input :notes, :input_html => { :rows => 5, :cols => 70 } %>
<div class="form-actions">
<%= f.submit nil, :class => 'btn btn-primary' %>
<%= link_to 'Cancel', company_users_path, :class => 'btn' %>
</div>
</fieldset>
<% end %>
当我提交表单时,它会默默地失败,除了我在日志中注意到“roles_attributes”被传递为:
"roles_attributes"=>{"0"=>{"company_id"=>"2", "active"=>"1", "role"=>"Inspector"}}
我认为应该是:
"roles_attributes"=>[{"company_id"=>"2", "active"=>"1", "role"=>"Inspector"}]
我一定遗漏了一些明显的东西。