0
我有一點複雜的模型關聯的:嵌套形式複雜模型無法創建兒童
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"}]
我一定是失去了一些東西明顯。