在模型中使用连接表数据

时间:2016-06-13 17:44:40

标签: ruby-on-rails ruby activerecord

我有两个表:user_nutrients(包含user_id,营养素ID和整数金额)和nutrients(其中包含有关营养素的更多信息,如大卡,脂肪等)。我想创建一个“FoodCalculator”,它从user_nutrients和其他数据(比如说kcal)中取出nutrients来执行一些计算(用我当前用户的kcal乘以)。我可以检索属于某个用户的所有user_nutrients(通过def user_nutrients)但我的问题是我现在如何从FoodCalculator中的nutrients表中检索相应的数据?

现在已经挣扎了好几天了。对不起,如果我的问题可能太简单或没有得到很好的解释。几个月前刚开始编码。

food_calculator.rb

class FoodCalculator
  def initialize(user)
     @user = user
  end

  def user_nutrients
    @user_nutrients ||= @user.user_nutrients
  end
end

nutrient.rb

class Nutrient < ActiveRecord::Base
  validates :name, uniqueness: true
  has_many :user_nutrients
  has_many :users, through: :user_nutrients
end

user_nutrient.rb

class UserNutrient < ActiveRecord::Base
  belongs_to :user 
  belongs_to :nutrient
end

user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  after_create :create_profile
  after_create :programstart

  has_one :profile, dependent: :destroy
  has_many :weights, dependent: :destroy
  has_many :programstarts, dependent: :destroy

  has_many :user_nutrients
  has_many :nutrients, through: :user_nutrients


  private

  def programstart
    Programstart.create(:user_id => id)
  end

end

2 个答案:

答案 0 :(得分:1)

因为有很多用户与营养素的关系

@user_nutrients ||= @user.nutrients

应该有效

答案 1 :(得分:0)

使用@user.user_nutrients

从用户检索数据时

您也可以使用@nutrient.user_nutrients

进行检索

如果想要用户查找营养素而不是使用@user.nutrients

您也可以通过营养来找到比用户@nutrient.users

更多的用户