ruby和rails在belongs_to的模型中定义实例变量

时间:2014-05-14 20:40:16

标签: ruby-on-rails ruby ruby-on-rails-4 model instance-variables

我有以下一些代码可以正常工作。

# app/models/course.rb
class Course < ActiveRecord::Base
    has_many :lessons, :dependent => :destroy
end

# app/models/lesson.rb
class Lesson < ActiveRecord::Base
    belongs_to :course

    def previous
        lessons = self.course.lessons.order('date')
        index = lessons.index(self)

        if (index == 0)
            return nil
        else
            lessons.at(index - 1)
        end
    end

    def next
        lessons = self.course.lessons.order('date')
        index = lessons.index(self)

        if (index + 1) == lessons.length
            return nil
        else
            lessons.at(index + 1)
        end
    end
end

问题是lessonsindex的定义是多余的。我试着把它们拉得越来越高。在范围但没有骰子:

class Lesson < ActiveRecord::Base
    belongs_to :course

    lessons = self.course.lessons.order('date')
    index = lessons.index(self)

    def previous
        if (index == 0)
            return nil
        else
            lessons.at(index - 1)
        end
    end

    def next
        if (index + 1) == lessons.length
            return nil
        else
            lessons.at(index + 1)
        end
    end
end

FWIW,我最近编写了相当多的JavaScript代码,并在经历了漫长的(6年)休假之后回到了Ruby和Rails。我想我试图强迫关闭Ruby,但我真的不知道我做错了什么。

我已经找了一段时间,因为我无法在正典中找到任何有用的问题/答案,我以为我会问。

1 个答案:

答案 0 :(得分:0)

class Lesson < ActiveRecord::Base

  ...

  def lessons
    course.lessons.order('date')
  end

  def index
    lessons.index(self)
  end

  ...

end