我有我的訂單控制器這個動作:重構模型
# POST /orders
# POST /orders.json
def create
@order = Order.new(params[:order])
#spostare il ciclo cart > line_items come metodo del modello Order
cart = session[:cart]
cart.each do | id, quantity |
item = Project.find_by_id(id)
@line_item = LineItem.new
@line_item.project = item
@line_item.quantity = quantity
@line_item.price = item.price
@order.line_items << @line_item
end
@order.user = current_user
session.delete(:cart)
respond_to do |format|
if @order.save
#Send an email to admin
UserMailer.order_created_to_admin(@order).deliver
format.html { redirect_to :dashboard, notice: "L'ordine è stato creato correttamente." }
format.json { render json: @order, status: :created, location: @order }
else
format.html { render action: "new" }
format.json { render json: @order.errors, status: :unprocessable_entity }
end
end
end
現在我要重構它一點,我想移動下面的幾行命令模式的方法:
cart.each do | id, quantity |
item = Project.find_by_id(id)
@line_item = LineItem.new
@line_item.project = item
@line_item.quantity = quantity
@line_item.price = item.price
@order.line_items << @line_item
end
這樣的:
class Order < ActiveRecord::Base
attr_accessible :user_id
belongs_to :user
has_many :line_items, :dependent => :destroy
accepts_nested_attributes_for :line_items, :allow_destroy => true
def add_line_items_to_order_from_cart(cart) do
cart.each do | id, quantity |
item = Project.find_by_id(id)
@line_item = LineItem.new
@line_item.project = item
@line_item.quantity = quantity
@line_item.price = item.price
line_items << @line_item
end
end
end
和控制器喜歡叫它:
order.add_line_items_to_order_from_cart(cart)
從「瘦身控制器/胖模特」的模式來講它有意義嗎?
謝謝
編輯
我的訂單現在模型:
class Order < ActiveRecord::Base
attr_accessible :user_id
belongs_to :user
has_many :line_items, :dependent => :destroy
accepts_nested_attributes_for :line_items, :allow_destroy => true
validates :user, :presence => :true
def add_line_items_to_order_from_cart(cart)
cart.each do | id, quantity |
item = Project.find(id)
line_items << LineItem.new(project: item,
quantity: quantity,
price: item.price)
end
end
end
是的,它真的有道理!我是'瘦控制器/胖模式'模式的粉絲:) –
嗨@BlueSmith,謝謝!我在想,所有那些「調用」其他模型Project和LineItems可能是模型中的一個問題。 – enricostn