class Lesson < ActiveRecord::Base
...
def lessons
course.lessons.order('date')
end
def index
lessons.index(self)
end
...
end
ruby and rails define instance variable in model for belongs_to
-
22-07-2023 - |
質問
I have the following bit of code that works just fine.
# 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
The problem is that the definitions of lessons
and index
are redundant. I tried to just pull them 'higher' in scope but no dice:
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, I've been coding quite a bit of JavaScript recently and just returned to Ruby and Rails after a looooong (6 year) hiatus. I think I'm trying to force closure on Ruby but I really dunno what I'm doing wrong.
I've looked for a while and since I couldn't find any useful questions/answers in the canon I thought I'd ask.
解決
所属していません StackOverflow