ruby on rails - Use join table data in model -


i have 2 tables: user_nutrients (that holds user_id, nutrient_id , amount integer) , nutrients (that holds more information on nutrients, kcal, fat etc.). want create "foodcalculator" takes amount user_nutrients , other data (let's kcal) nutrients perform calculations (multiply amount kcal current user). can retrieve user_nutrients belong user (through def user_nutrients) question how can retrieve corresponding data nutrients table in foodcalculator?

been struggling several days. sorry if question may simple or not explained. 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 , :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 

as there's has many through relationship of user nutrients

@user_nutrients ||= @user.nutrients

should work


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -