Basic app. Trying to make a button that clicks and shows the next page in this case lesson.
In my controller I have:
def show
@lesson = Lesson.find(params[:id])
end
In my view (show.html.erb) I have:
...
<p><%= link_to 'Previous', Lesson.previous(@lesson) %></p>
<p><%= link_to 'Next', Lesson.next(@lesson) %></p>
...
In my model I have:
def self.next(current_lesson)
current_lesson.number + 1
end
def self.previous(current_lesson)
current_lesson.number - 1
end
My schema includes a number column that is an integer.
However, this errors out with 'undefined method `to_model' for 0:Fixnum' and when I run @lesson in the console, it comes up as nil.
I also tried this:
def self.next
current_lesson = Lesson.find(@lesson.id)
next_lesson = current_lesson.number + 1
end
def self.previous
current_lesson = Lesson.find(@lesson.id)
previous_lesson = current_lesson.number - 1
end
This however, successfully passes the model the instance variable because in the console @lesson returns the correct value but it cannot call the method.
thoughts?
Edit: another solution attempted:
I tried changing this to an instance method rather than a class method. So in the view I set @lesson.previous and @lesson.next. In the model I did this:
def next
self.number + 1
end
def previous
self.number - 1
end
But alas, I get @instance nil error again.
self.next & self.previous return integer instead of Lesson. Make them return next and previous Lesson objects and it should work. Ie
Lesson.find_by_number(self.number-1)
In the function
def self.next
current_lesson = Lesson.find(@lesson.id)
next_lesson = current_lesson.number + 1
end
you will return a Fixnum instead of a Lesson object.
If you want to return a Lesson with an id 1 higher you are probably better off doing something like:
def next
Lesson.find(self.number + 1)
end
The reason why you're getting the error is that Lesson.next
and Lesson.previous
return integers and not lesson objects. If you wanted to continue using the next
and previous
class methods, you could make the following change in your view
<p><%= link_to 'Previous', lesson_path(Lesson.previous(@lesson)) %></p>
<p><%= link_to 'Next', lesson_path(Lesson.next(@lesson)) %></p>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.