0
我是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
作用。 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 %>
感谢您的回复@Qumara。我会读它 同时,如果你有线索解决它,请做。再次感谢! – Sudhakar
看起来你应该首先创建一个连接表来存储roles_id和employes_id的所有组合。 (在这里你可以阅读它):http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many。我在你的散列中看到有“role_ids”=> [“”,“4”],它需要一个值,你应该提供。 –
我已经创建了一个连接表roles_users。我甚至可以在下拉列表中看到角色列表,但提交后选定的值没有通过。我怀疑创建方法(在问题中更新)是罪魁祸首,但经过大量的谷歌搜索,我仍然无法弄清楚为什么价值不传递给模型 – Sudhakar