我的订单控制器中有此操作:
# 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
现在我想对其进行一些重构,并且正在考虑将以下几行移至 Order Model 作为一种方法:
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