我编写了一个表单对象来填充订单、账单和送货地址对象。该populate
方法看起来非常冗长。由于表单字段不直接对应地址属性,我被迫手动分配它们。例如:
shipping_address.name = params[:shipping_name]
billing_address.name = params[:billing_name]
这是对象。请注意,为简洁起见,我剪掉了大多数地址字段和验证,以及其他一些代码。但这应该给你一个想法。注意填充方法:
class OrderForm
attr_accessor :params
delegate :email, :bill_to_shipping_address, to: :order
delegate :name, :street, to: :shipping_address, prefix: :shipping
delegate :name, :street, to: :billing_address, prefix: :billing
validates :shipping_name, presence: true
validates :billing_name, presence: true, unless: -> { bill_to_shipping_address }
def initialize(item, params = nil, customer = nil)
@item, @params, @customer = item, params, customer
end
def submit
populate
# snip
end
def order
@order ||= @item.build_order do |order|
order.customer = @customer if @customer
end
end
def shipping_address
@shipping_address ||= order.build_shipping_address
end
def billing_address
@billing_address ||= order.build_billing_address
end
def populate
order.email = params[:email]
shipping_address.name = params[:shipping_name]
shipping_address.street = params[:shipping_street]
# Repeat for city, state, post, code, etc...
if order.bill_to_shipping_address?
billing_address.name = params[:shipping_name]
billing_address.street = params[:shipping_street]
# Repeat for city, state, post, code, etc...
else
billing_address.name = params[:billing_name]
billing_address.street = params[:billing_street]
# Repeat for city, state, post, code, etc...
end
end
end
这是控制器代码:
def new
@order_form = OrderForm.new(@item)
end
def create
@order_form = OrderForm.new(@item, params[:order], current_user)
if @order_form.submit
# handle payment
else
render 'new'
end
end
不,我不感兴趣accepts_nested_attributes_for
,这带来了几个问题,因此我编写了表单对象。