Ruby on rails 如何在类之间移动变量
我有两门课:Ruby on rails 如何在类之间移动变量,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有两门课: class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable has_many :cals has_many :employees , through: :cals ........ end class用户
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
has_many :cals
has_many :employees , through: :cals
........
end
class用户
,第二项:
class Employee < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
belongs_to :user
has_one :cal
has_one :user , through: :cal
after_save :ids
def ids
if self.role == 'employee'
Cal.create(
user_id: @user.id
employee_id: self.id
)
end
....
end
类Employee
问题:
当我保存或调用函数“ids”时,我收到一个错误,因为“class Employee”无法识别“@user.id”,我该如何解决这个问题 试试看:
def ids
if role == 'employee'
Cal.create(
user_id: user.id
employee_id: id
)
end
end
从现有类中创建子类,而不是重新创建Rails:
class Employee < ActiveRecord::Base
...
class Employee
注意
在这个答案发布后的某个时候,OP改变了这个问题。此答案是对原始问题的回答。您可以将
当前用户.id
替换为@user.id将@user
替换为用户
,无需在方法前面加上self
btw+1。我喜欢这个答案。OP的代码甚至不会工作,除非类ActiveRecord::Baser
存在。我不明白你的答案,能不能进一步扩展?