尝试访问模型轨道中的相关记录时的未定义方法3

时间:2011-03-09 06:57:43

标签: ruby-on-rails

我的模型有什么问题,使用rails 3.0.5和ruby 1.9.2?

class Milestone < ActiveRecord::Base

  has_many :capstone_milestones
  has_many :capstones, :through => :capstone_milestones
  belongs_to :department
  attr_accessible :id, :name, :description, :department_id, :project

  accepts_nested_attributes_for :capstone_milestones, :allow_destroy => true

  def before_create # or after_initialize
    self.project ||= 'Default'
  end

  def xpos
    (Milestone.department.id - 100000)*100
  end
end

当我在视图中执行milestone.xpos时,我收到“未定义的方法`部门'”错误消息。

THX!

1 个答案:

答案 0 :(得分:2)

您无法按类名访问部门,因为您将其作为实例方法获取。 您可以访问

@milestone = Milestone.find(id)
@milestone.department_id

In your case just replace Milestone with self.

(self.department.id - 100000)*100