[英]Passing instance variable from Model to View to Controller in Rails
基本應用。 在這種情況下,嘗試使按鈕單擊並顯示下一頁。
在我的控制器中,我有:
def show
@lesson = Lesson.find(params[:id])
end
在我看來(show.html.erb)我有:
...
<p><%= link_to 'Previous', Lesson.previous(@lesson) %></p>
<p><%= link_to 'Next', Lesson.next(@lesson) %></p>
...
在我的模型中,我有:
def self.next(current_lesson)
current_lesson.number + 1
end
def self.previous(current_lesson)
current_lesson.number - 1
end
我的架構包括一個數字列,它是一個整數。
但是,使用“未定義的方法'to_model'為0:Fixnum'會出此錯誤,當我在控制台中運行@lesson時,它顯示為nil。
我也試過這個:
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
但是,這成功地將實例變量傳遞給模型,因為在控制台中@lesson返回正確的值,但是它無法調用該方法。
有什么想法嗎?
編輯:嘗試了另一種解決方案:
我嘗試將其更改為實例方法而不是類方法。 因此,在視圖中,我設置了@ lesson.previous和@ lesson.next。 在模型中,我這樣做:
def next
self.number + 1
end
def previous
self.number - 1
end
但是可惜,我再次收到@instance nil錯誤。
self.next和self.previous返回整數,而不是Lesson。 使他們返回下一個和上一個Lesson對象,它應該起作用。 即
Lesson.find_by_number(self.number-1)
在功能上
def self.next
current_lesson = Lesson.find(@lesson.id)
next_lesson = current_lesson.number + 1
end
您將返回一個Fixnum而不是一個Lesson對象。
如果您想返回ID為1的課程,則最好執行以下操作:
def next
Lesson.find(self.number + 1)
end
出現錯誤的原因是Lesson.next
和Lesson.previous
返回整數而不是課程對象。 如果您想繼續使用next
和previous
類方法,則可以在視圖中進行以下更改
<p><%= link_to 'Previous', lesson_path(Lesson.previous(@lesson)) %></p>
<p><%= link_to 'Next', lesson_path(Lesson.next(@lesson)) %></p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.