用户和练习之间的关系是用户 has_many 锻炼 belongs_to 用户
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
我收到错误:&#34; 未定义方法`user&#39;对于#&#34;
这是我的用户模型
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
感谢您的帮助
答案 0 :(得分:2)
Rails会自动为您提供从练习实例导航到用户的访问者。在calor_burned
方法中,您应该能够执行user.id或user_id。
如果这些方法不可用,请确认类User提及has_many :exercises
并且您是否进行了正确设置两个表的迁移?确认在您的数据库中,exercise有一个名为“user_id”的列,它应该是一个外键到users表。