0

User和Exercise的关系是user has_many exercise 而executive belongs_to user

class Exercise < ActiveRecord::Base
 belongs_to :user
 attr_accessible :act_id, :bcalor, :comment, :day, :week, :duration

 before_save :calor_burned

 private

 def calor_burned
  act = Activity.find(act_id)
  #how to find user_id?
  #User has_many weeklyweight
  #and weeklyweight belongs to a user 
  wt = (Weeklyweight.where(:week => week, :user_id => user_id).first).weight
  if(wt < 180)
    self.bcalor = ((wt * act.w160 * duration)/60)
   elsif ((wt >= 180) && (wt < 220))
    self.bcalor = ((wt * act.w200 * duration)/60)
   else
    self.bcalor = ((wt * act.w240 * duration)/60)
   end
  end 
 end

如何访问帮助我访问体重的user.id ?

编辑

我正在努力

user = act.user

我收到错误消息:“未定义的方法 `user' for #

编辑

这是我的用户模型

class User < ActiveRecord::Base

  attr_accessible :name, :provider, :uid

 # This is a class method, callable from SessionsController
 # hence the "User."
 def User.create_with_omniauth(auth) 
   user = User.new()
   user.provider = auth["provider"]
   user.uid = auth["uid"]
   user.name = auth["info"]["name"]
   user.save
   return user
  end

  has_one :userprofile
  has_many :exercises
  has_many :weeklyweights
end

感谢您的帮助

4

1 回答 1

2

Rails 将自动为您提供从练习实例导航到用户的访问器。在您的calor_burned方法中,您应该能够执行 user.id 或 user_id。

如果这些方法不可用,请确认 User 提到的类has_many :exercises,并且您是否有正确设置两个表的迁移?确认在您的数据库中,练习有一个名为“user_id”的列,它应该是用户表的外键。

于 2012-12-02T22:03:43.077 回答