I’m looking for best practices. Here’s the scenario:
Customers can pay for one or more Widgets from a form. So I have a Payments model and a Widgets model. There is no association between them (Payments is associated with Customer). What’s the best way to handle this?
In the Payments controller I could do:
def create
@customer = Customer.find(params[:customer_id])
if @customer.payments.create!(params[:payment])
how-many-widgets = params[:payment][:number].to_i
while how-many-widgets > 0
widget = Widgets.new
... update widget ...
widget.save!
how-many-widgets = how-many-widgets - 1
end
end
redirect_to @customer
end
Is this the best way to do this? Or is there some more elegant solution?
If you’re saving and changing things, it’s a good bet you should be doing this code in a model, rather than a controller. If I were to refactor your code, it would look a little like this:
If
Widget.createisn’t what you’re looking for, come up with a custom method that takes the params in, transforms them, and then spits out the correct object. Also if the widgets should be related to either the customer or payments, don’t hesitate to relate them — like, if you look at that code and say, “I also need to pass the current user/customer/payment to the widget,” that would be a good hint that the widget should be associated to that model somehow.