我正在做一些我认为非常简单的事情,最终变得非常复杂。我已按照此Railscasts创建了一个多步骤表单。现在我正在尝试在Order
视图中嵌套表单以创建父Customer
(如果其中尚未存在)(请参阅this问题)。
基本上,我希望创建一个客户来拥有订单(如果它们尚不存在)。我是以错误的方式解决这个问题吗?
目前,我得到了
无法批量分配受保护的属性:customer_attributes
当我有订单belongs_to :customers
时。但那对我来说似乎最合乎逻辑?我把代码放在下面。
客户模式:
class Customer < ActiveRecord::Base
attr_accessible :address_1, :address_2, :email, :name, :phone, :user_id
belongs_to :user
end
订单型号:
class Order < ActiveRecord::Base
attr_accessible :customer_id, :format, :message, :phone, :quantity
belongs_to :customer
accepts_nested_attributes_for :customer
attr_writer :current_step
...
相关订单控制器方法:
# GET /orders/new
# GET /orders/new.json
def new
session[:order_params] ||= {}
@order = Order.new(session[:order_params])
@order.build_customer(session[:order_params])
@order.current_step = session[:order_step]
end
# POST /orders
# POST /orders.json
def create
session[:order_params].deep_merge!(params[:order]) if params[:order]
@order = Order.new(session[:order_params])
@order.current_step = session[:order_step]
if params[:back_button]
@order.previous_step
elsif @order.last_step?
@order.save
else
@order.next_step
end
session[:order_step] = @order.current_step
if @order.new_record?
render 'new'
else
session[:order_step] = session[:order_params] = nil
flash[:notice] = "Order saved."
redirect_to @order
end
end
视图/命令/新
%h1 New order
= form_for(@order) do |f|
- if @order.errors.any?
#error_explanation
%h2
= pluralize(@order.errors.count, "error")
prohibited this order from being saved:
%ul
- @order.errors.full_messages.each do |msg|
%li= msg
= render "#{@order.current_step}_step", :f => f
= f.submit "Continue"
= f.submit "Back", :name => "back_button" unless @order.first_step?
我正在尝试嵌套表单的部分视图:
.field
= f.label :quantity
= f.text_field :quantity
%h3
Customer details
=f.fields_for :customer do |builder|
=builder.label :name
=builder.text_field :name
=builder.label :email
=builder.text_field :email
希望这就是一切。我以前做过嵌套表单,但从未与多步表单组合。任何帮助都会非常感激。
答案 0 :(得分:1)
是的,你需要两个:
attr_accessible :customer_attributes, :customer_id, :format, :message, :phone, :quantity
accepts_nested_attributes_for :customer
attr_accessible
告诉Rails允许的属性区域。
accepts_nested_attributes_for
告诉rails将属性委托给另一个类。