我是一个RoR新手。我无法创建具有指定角色的新员工。 从下面的服务器日志中我发现记录没有被保存,因为" role_ids"是空白但我无法理解为什么" role_ids"传递而不是"角色"
我觉得这可能是一线修复。请帮我解决这个问题。提前感谢您的时间。
Processing by EmployeesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Nf9Ti9vdr0ErvJV3LKoErT6dMoUwWAI5eJVBOUISZxo=", "employee"=> {"name"=>"dvxzv", "role_ids"=>["", "4"], "reports_to"=>"Adam"}, "commit"=>"Create Employee"}
(0.1ms) begin transaction
(0.0ms) rollback transaction
Role Load (0.2ms) SELECT "roles".* FROM "roles" ORDER BY title
Role Load (0.1ms) SELECT "roles".* FROM "roles"
Rendered employees/_form.html.erb (8.9ms)
注意" role_ids"在上面一行中,我不确定为什么会采用role_ids而不是'角色'属性
Employee.rb
class Employee < ActiveRecord::Base
attr_accessible :name, :role, :reports_to, :role_ids
validates :name, :presence => true, :length => { :maximum => 20 }
belongs_to :company
has_and_belongs_to_many :roles
end
Role.rb
class Role < ActiveRecord::Base
attr_accessible :title
has_and_belongs_to_many :employees
end
employees_controller.rb
def create
@employee = User.new(params[:user])
@role = @employee.roles.build(params[:role]) unless @user.roles.build(params[:role]).blank?
respond_to do |format|
if @employee.save
format.html { redirect_to @employee, notice: 'Employee was successfully created.' }
format.json { render json: @employee, status: :created, location: @employee }
else
format.html { render action: "new" }
format.json { render json: @employee.errors, status: :unprocessable_entity }
end
end
end
_form.html.erb
<%= simple_form_for(@employee, :html => {:class => 'form-horizontal' }) do |f| %>
<fieldset>
<legend><%= controller.action_name.capitalize %> Employee</legend>
<div class="control-group">
<%= f.label :name, :class => 'control-label' %>
<div class="controls">
<%= f.input :name, :label => false %>
</div>
</div>
<div class="control-group">
<%= f.label :role, :class => 'control-label' %>
<div class="controls">
<%= f.association :roles, :collection => Role.all(:order => 'title'), :label_method => :id, :prompt => "Assign role", :label => false %>
</div>
</div>
<div class="control-group">
<%= f.label :reports_to, :class => 'control-label' %>
<div class="controls">
<%= f.input :reports_to, :collection => [ "Sam", "Adam", "Smith"], :prompt => "Select supervisor", :label => false %>
</div>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
</fieldset>
<% end %>
答案 0 :(得分:0)
您可能需要考虑阅读Rails Guide on nested resources。
如果你想让事情变得更加轻松,我强烈建议你研究一下Jose Valim的Inherited Resources gem,它会为你解决很多这样的漏洞。