Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在类之间移动变量_Ruby On Rails_Ruby - Fatal编程技术网

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
存在。我不明白你的答案,能不能进一步扩展?