I'm builing a weight loss app. For this in my app each user has_one :profile and has_many :weights. Each profile belongs_to :pal. For my app to work I need a value called SMR which basically is a formula that takes as variables the user's size, age and gender (all from profiles table), the user's current weight (from weights table) as well as a float number from pal table.
I am able to calculate SMR in profiles_controller.rb show action and show it in the profiles show.html.erb.
I have two questions now:
profiles_controller.rb show action or should I do it in the profile.rb model? If I should do it in the model: how can I do it (how should the code look like)?I'm fairly new to the Rails world so maybe my questions are really noob questions.
profile.rb
class Profile < ActiveRecord::Base
belongs_to :user
belongs_to :pal
belongs_to :goal
def age
if birthdate != nil
now = Time.now.utc.to_date
now.year - birthdate.year - (birthdate.to_date.change(:year => now.year) > now ? 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 you should create a separate class or you can do on profile model as 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 this class on your controller show method like this:
@smr_calculator = SmrCalculator.new(@profile, current_user)
@smr = @smr_calculator.get_smr
And add this class as smr_calculator.rb in models folder
so anywhere in the app you need @smr you can call this class with profile and current user
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With