如何在类之间移动变量

时间:2014-03-25 12:53:03

标签: 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 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

问题/问题:

当我保存或致电功能&#34; ids&#34;我收到错误是因为 - &#34;班级员工&#34;不承认&#34; @ user.id&#34;,我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

尝试:

def ids 
  if role == 'employee'
    Cal.create(
      user_id: user.id
      employee_id: id
    )
  end
end

答案 1 :(得分:1)

来自现有类的子类,而不是重新发明Rails:

class Employee < ActiveRecord::Base
  ...

注意

在发布此答案后,OP已经改变了问题。这个答案是对原始问题的回答。

答案 2 :(得分:-1)

您可以current_user.id代替@user.id