accepts_nested_attributes_for无法正常工作

时间:2012-01-02 01:29:26

标签: ruby-on-rails-3.1 nested-attributes

我有一个work_order模型和里程表模型。我正在尝试为每个工单添加里程表读数,但还需要能够添加里程表读数而无需将工作订单与其关联。

我的模型设置如下:

#odometer.rb
class Odometer < ActiveRecord::Base
  has_one :work_order
  accepts_nested_attributes_for :work_order
end

#work_order.rb
class WorkOrder < ActiveRecord::Base
  belongs_to :odometer
end

我的表单设置如下:

    = form_for @work_order do |f|
      = f.label :created_at, "Start Date"
      = f.text_field :created_at, :class => "datepicker", :value => @work_order.created_at.nil? ? '' : @work_order.created_at.strftime('%Y-%m-%d')
      %br
      = f.label :number, "Work Order #"
      = f.text_field :number
      %br 
      = f.label :complete_date, "Finish Date"
      = f.text_field :complete_date, :class => "datepicker", :value => @work_order.complete_date.nil? ? '' : @work_order.complete_date.strftime('%Y-%m-%d')
      %br
      = f.label :mechanic_id
      = f.collection_select :mechanic_id, @mechanics, :id, :display_name

      = f.fields_for :odometer do |o|
        = o.label :mileage
        = o.number_field :mileage
      = f.label :equipment_id
      = f.collection_select :equipment_id, @all_equipment, :id, :name

      = f.label :description
      = readable_text_area f, :description, :style => "width:630px;height:100px;"

      = f.submit 'Save'

我似乎无法通过这个来保存里程表的东西。我确信我做的事情完全错了,但我无法弄清楚。

感谢您的帮助。

托比

1 个答案:

答案 0 :(得分:1)

看起来表格有点回到前面。根据模型,Odometer接受WorkOrder的嵌套属性。但形式告诉我这是相反的方式。

结帐此Railscast http://railscasts.com/episodes/196-nested-model-form-part-1