Reputation: 11
Hello I'm new in RoR. How can I switch my simple controller logic to the model? My database columns is order_type, quantity, quantity_adjusted
Controller
def create
@product = Product.new(params[:product])
# This is the control structure I want to move to Model
if @product.order_type = "Purchase"
@product.quantity_adjusted = -quantity
else
@product.quantity_adjusted = quantity
end
end
Model
class Product < ActiveRecord::Base
end
Thanks LH
Upvotes: 1
Views: 659
Reputation: 43298
You could use a callback in your model. E.g. after_create
.
Controller:
def create
@product = Product.new(params[:product])
if @product.save
# redirect
else
render :new
end
end
Model:
class Product < ActiveRecord::Base
after_create :adjust_quantity
private
def adjust_quantity
if self.order_type == "Purchase"
self.quantity_adjusted = -quantity
else
self.quantity_adjusted = quantity
end
end
end
Upvotes: 0
Reputation: 48626
There are many ways to do it. One way, possible the most natural, is to create an instance method like :
def adjust_quantity(amount)
(put logic here)
end
in your Product model. Then in your controller, you would do :
@product.adjust_quantity(quantity)
Upvotes: 2