upon creation of list of quantities, list attribute total_calories should updated sum of calories associated list. lists , foods associated has_many :through quantities, , each food has calories attribute.
when create list in rails development user interface hosted c9.io, behaves expected. when create list in console, not; total_calories not updated. how be?
i appreciate tips investigate, have never encountered issue of inconsistency between console , development user interface.
the service object count_calories.rb:
class countcalories def initialize(list) @list=list end def count @calories = 0 @list.quantities.each |q| @calories += food.find(q.food_id).calories end @list.update!(total_calories: @calories) @list.save! end end the create method in list controller:
def create @list = writelist.new(list_params).write if @list.save flash[:success] = "a list has been created!" countcalories.new(@list).count redirect_to @list else render 'new' end end the service object write_list.rb, in case helpful:
class writelist def initialize(params) @params=params end def write activerecord::base.transaction list = list.new(days: @params[:days], name: @params[:name]) list.save! 3.times food1 = food.all.sample.id quantity.create!(food_id: food1, list_id: list[:id], amount: 1+rand(6)) end list.save! return list end rescue return list.new(days: @params[:days], name: @params[:name]) end end the thing can think of maybe has migration create total_calories:
class addtotalcaloriestolists < activerecord::migration def change add_column :lists, :total_calories, :integer, :default => 0 end end but mostly, baffled , appreciate tips.
i believe have on engineered problem. appears coming java web stack , it's done differently in rails way. avoid service objects if don't need them.
class food < activerecord::base validates_presence_of :calories has_many :lists, through: :food_lists, :dependent: :destroy end class foodlist < activerecord::base belongs_to :food belongs_to :list validates_presence_of: :amount, :food, :list end class list < activerecord::base has_many :food_lists has_many :foods, through: :food_lists, dependent: :destroy def total_calories self.food_lists.map{|fl| fl.amount * fl.food.calories}.sum end end things can calculated on fly, should calculated, store them form of optimization if really need to. makes business domain easier debug , support. maintaining state last resort!
Comments
Post a Comment