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