Oliver
Oliver

Reputation: 1181

Use join table data in model

I have two tables: user_nutrients (that holds a user_id, nutrient_id and an amount as integer) and nutrients (that holds some more information on nutrients, like kcal, fat etc.). I want to create a "FoodCalculator" that takes the amount from user_nutrients and other data (let's say kcal) from nutrients to perform some calculations with it (multiply amount with kcal for my current user). I can retrieve all user_nutrients that belong to a certain user (through def user_nutrients) but my question is how I can now retrieve the corresponding data from the nutrients table in my FoodCalculator?

Been struggling with this now for several days. Sorry if my question may be too simple or not well explained. Just started coding few months ago.

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

Upvotes: 0

Views: 54

Answers (2)

ashishmohite
ashishmohite

Reputation: 1120

As there's Has many through relationship of user with nutrients

@user_nutrients ||= @user.nutrients

should work

Upvotes: 1

Sourabh Ukkalgaonkar
Sourabh Ukkalgaonkar

Reputation: 156

As you retrieve data from user by using @user.user_nutrients

In same manner you can retrieve by using @nutrient.user_nutrients

and if want find nutrients by user than you may use @user.nutrients

and you may also find users by nutrient than user @nutrient.users

Upvotes: 0

Related Questions