Activerecord:如何在Belong_to关系中从一个对象导航到另一个对象



用户和Exercise之间的关系是用户有_many锻炼,而锻炼属于用户

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'">

编辑

这是我的用户模型

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

感谢您帮助

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

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

最新更新