i barely understand rails, let alone ruby, easy one. in 1 of controller's show action have variable have defined calculate total of items, looks this:
@total_of_items = somemodel.where(:user_id => @user).sum(:amount)
this collects of amount attributes of particular user , adds them up. in view call:
<%= @total_of_items %>
and shows up. 2 questions. first, best way this? because may want take value , show in user's view compare two, or that. seems in order have method in model? i'm not sure.
my second question how take variable defined in controller , put in model. seems that's more "skinny controller fat model" way of doing things. little help?
you can simplify controller creating scope (as @apneadiving demonstrates), or method encapsulates query:
def self.amount_sum(user) where(:user_id => user).sum(:amount) end
then in controller:
@total_of_items = somemodel.amount_sum(@user)
in case use method, because scope little harder read. ryan bates makes note of in railscast 215:
in second named scope we’re using lambda. if ever use 1 of these in named scope might consider using class method instead if you’re passing in large number of parameters or if content of scope complex. ours simple we’ll turn class method anyway.
your case pretty simple, i'd consider placing logic inside class method.
Comments
Post a Comment