Ruby on rails 3 具有复杂模型的嵌套表单无法创建子项
我有一点复杂的模型关联:Ruby on rails 3 具有复杂模型的嵌套表单无法创建子项,ruby-on-rails-3,nested-attributes,Ruby On Rails 3,Nested Attributes,我有一点复杂的模型关联: 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_attribut
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
以及以下观点:
<%= 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"=>[{"company_id"=>"2", "active"=>"1", "role"=>"Inspector"}]
我一定错过了什么明显的东西。原来是
有安全的密码。我已删除密码字段,验证失败
"roles_attributes"=>{"0"=>{"company_id"=>"2", "active"=>"1", "role"=>"Inspector"}}
"roles_attributes"=>[{"company_id"=>"2", "active"=>"1", "role"=>"Inspector"}]