我正在尝试在我的 Ruby on Rails 应用程序中构建一个 simple_nested_form。当我提交表单时,我收到一些未知错误,因为它只是重定向回表单以再次输入。这是我提交表单时 Rails 服务器控制台中的输出。看起来那里有一些随机的“0”=>。
Parameters: {"machine"=>{"name"=>"2134", "ip_adress"=>"2", "machine_employees_attributes"=>{"0"=>{"machine_id"=>"1", "employee_id"=>"2"}}}, "commit"=>"Create Machine"}
我有一个机器模型 has_many :machine_employees
和一个属于_to :machine 的machineemployee 模型
你知道为什么这个 0 => 会出现吗,因为我认为这是给我带来问题的原因。
这是我的模型的代码。
机器
class Machine < ActiveRecord::Base
# Relationships
has_many :machine_employees
has_many :employees, :through => :machine_employees
accepts_nested_attributes_for :machine_employees, :reject_if => lambda{ |me| me[:employee_id].blank? }
attr_accessible :ip_adress, :name, :machine_employees_attributes
# Validations
validates_presence_of :name, :ip_adress
end
机器员工
class MachineEmployee < ActiveRecord::Base
before_validation :set_default
# Relationships
belongs_to :machine
belongs_to :employee
attr_accessible :employee_id, :machine_id, :end_date, :start_date
# Validations
validates_presence_of :employee_id, :machine_id, :start_date
private
# Callback Methods
def set_default
self.start_date = Date.today
self.end_date = nil
end
end
新机形态
<div class="row-fluid">
<div class="span3">
<h1>Add a Machine</h1>
<br />
<%= simple_nested_form_for @machine do |f| %>
<%= render "machine_fields", :f => f %>
<%= f.button :submit %>
<%= link_to 'Back', machines_path %>
</div>
<div class="span4">
<h4>Assign an Employee to This Machine</h4>
<%= f.simple_fields_for :machine_employees do |me_form| %>
<!-- render nested machine_employee fields-->
<%= render "machine_employee_fields", :f => me_form %>
<% end %>
</div>
<% end %>
</div>
机器员工字段部分
<%= f.input :machine_id, :as => :hidden, :input_html => { :value => @machine.id } %>
<%= f.input :employee_id, collection: @employees, :id => :name, :prompt => "Select ..." %>