ruby on rails - Calculation in model or controller -
i'm builing weight loss app. in app each user has_one :profile
, has_many :weights
. each profile belongs_to :pal
. app work need value called smr formula takes variables user's size, age , gender (all profiles table), user's current weight (from weights table) float number pal table.
i able calculate smr in profiles_controller.rb
show action , show in profiles show.html.erb.
i have 2 questions now:
- is correct calculation in
profiles_controller.rb
show action or should inprofile.rb
model? if should in model: how can (how should code like)? - i need smr value later on in app variable other calculations well. how can achieve (if calculated in profile controller/model needed somewhere else later on)?
i'm new rails world maybe questions noob questions.
profile.rb
class profile < activerecord::base belongs_to :user belongs_to :pal belongs_to :goal def age if birthdate != nil = time.now.utc.to_date now.year - birthdate.year - (birthdate.to_date.change(:year => now.year) > ? 1 : 0) else nil end end end
weight.rb
class weight < activerecord::base belongs_to :user end
pal.rb
class pal < activerecord::base has_many :profiles end
profiles_controller.rb (show action only)
def show @pal = @profile.pal @goal = @profile.goal @current_weight = weight.where(:user_id => current_user.id).order(:day).last if @profile.gender == 0 @smr = (10*@current_weight.kilograms+6.25*@profile.size-5*@profile.age+5)*@pal.value elsif @profile.gender == 1 @smr = (10*@current_weight.kilograms+6.25*@profile.size-5*@profile.age-161)*@pal.value else nil end end
i think should create separate class or can on profile model well
class smrcalculator def initialize(profile, user) @profile = profile @user = user end def get_smr @pal = @profile.pal @goal = @profile.goal @current_weight = weight.where(:user_id => @user.id).order(:day).last if @profile.gender == 0 @smr = (10*@current_weight.kilograms+6.25*@profile.size-5*@profile.age+5)*@pal.value elsif @profile.gender == 1 @smr = (10*@current_weight.kilograms+6.25*@profile.size-5*@profile.age-161)*@pal.value else nil end @smr end end
and call class on controller show method this:
@smr_calculator = smrcalculator.new(@profile, current_user) @smr = @smr_calculator.get_smr
and add class smr_calculator.rb in models folder
so anywhere in app need @smr can call class profile , current user