在模型或控制器中计算

Oli*_*ver 3 ruby-on-rails

我正在建立一个减肥应用程序.为此,在我的应用程序中每个用户has_one :profilehas_many :weights.每个档案belongs_to :pal.为了让我的应用程序工作,我需要一个名为SMR的值,它基本上是一个公式,它将用户的大小,年龄和性别(来自配置文件表),用户的当前权重(来自权重表)以及来自朋友桌.

我能够在profiles_controller.rbshow action中计算SMR,并在配置文件show.html.erb中显示它.

我现在有两个问题:

  1. profiles_controller.rbshow动作中进行此计算是正确的还是应该在profile.rb模型中进行?如果我应该在模型中这样做:我该怎么做(代码应该如何)?
  2. 稍后我会在我的应用程序中将SMR值作为其他计算的变量.我怎样才能实现这一点(如果它在配置文件控制器/模型中计算,但稍后需要在其他地方使用)?

我是Rails世界的新手,所以也许我的问题真的是noob问题.

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 
Run Code Online (Sandbox Code Playgroud)

weight.rb

class Weight < ActiveRecord::Base
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

pal.rb

class Pal < ActiveRecord::Base
  has_many :profiles
end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Tho*_*rin 5

我认为你应该创建一个单独的类,或者你也可以在profile模型上做

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
Run Code Online (Sandbox Code Playgroud)

并在您的控制器show方法上调用此类,如下所示:

@smr_calculator = SmrCalculator.new(@profile, current_user)
@smr = @smr_calculator.get_smr
Run Code Online (Sandbox Code Playgroud)

并在models文件夹中将此类添加为smr_calculator.rb

因此,在应用程序的任何位置,您需要@smr,您可以使用配置文件和当前用户调用此类