我使用的是带有has_one和has_many关系的嵌套表单。问题是关联中的数据没有被保存。
以下是模型,控制器和我正在使用的视图
卖单模型
class SellOrder < ActiveRecord::Base
belongs_to :company
has_one :work_order, dependent: :destroy
accepts_nested_attributes_for :work_order, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end
工单模型
class WorkOrder < ActiveRecord::Base
belongs_to :sell_order
has_many :todos, dependent: :destroy
accepts_nested_attributes_for :todos, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end
Todo模型
class Todo < ActiveRecord::Base
belongs_to :work_order
end
销售订单控制器
class SellOrdersController < ApplicationController
def new
@sell_order = SellOrder.new(user: current_user)
1.times {
@work_order = @sell_order.build_work_order
@work_order.todos.build
}
end
def create
@sell_order = current_company.sell_orders.new(sell_order_params)
if @sell_order.save
redirect_to [:edit, @sell_order]
else
1.times {
@work_order = @sell_order.build_work_order
@work_order.todos.build
}
render :new
end
end
private
def sell_order_params
params.require(:sell_order).permit(:some_other_attributes, work_order_attributes: [todos_attributes: [:comment, :price]])
end
end
查看
= f.fields_for :work_order do |builder_work_order|
= builder_work_order.fields_for :todos do |builder|
= builder.text_field :comment, class: 'form-control'
= builder.text_field :price, class: 'form-control'
当我提交表单时,只保存卖单。工作单和待办事项表中没有数据。有没有人有这种情况的解决方案?
Rails版本:4.1.1
提前致谢。