我正在构建一个减肥应用程序。为此,我的应用中的每个用户has_one :profile
和has_many :weights
。每个配置文件belongs_to :pal
。为了使我的应用正常工作,我需要一个名为SMR的值,该值基本上是一个公式,该公式将用户的大小,年龄和性别(全部来自配置文件表),用户的当前体重(来自体重表)以及朋友表。
我可以在profiles_controller.rb
表演动作中计算SMR并将其显示在个人资料show.html.erb中。
我现在有两个问题:
profiles_controller.rb
表演动作中进行此计算是否正确,还是应该在profile.rb
模型中进行计算?如果我应该在模型中执行此操作:如何执行(代码应如何显示)?我对Rails领域还很陌生,所以也许我的问题真的是菜鸟问题。
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
体重
class Weight < ActiveRecord::Base
belongs_to :user
end
pal.rb
class Pal < ActiveRecord::Base
has_many :profiles
end
profiles_controller.rb(仅显示操作)
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
我认为您应该创建一个单独的类,或者也可以对概要文件模型进行操作
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
并在控制器的show方法上调用此类,如下所示:
@smr_calculator = SmrCalculator.new(@profile, current_user)
@smr = @smr_calculator.get_smr
并将此类作为smr_calculator.rb添加到models文件夹中
因此,您需要在应用程序中的任何地方@smr都可以使用个人资料和当前用户来调用此类
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句