我寫了一個表單對象來填充一個Order,Billing和Shipping Address對象。 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
,其中存在幾個問題,因此爲什麼我寫的表單對象。
尼斯和companct +1!是%我只有Ruby 2.0? – Mohamad
是的。它是在Ruby 2.0中引入的。 – sawa