繁体   English   中英

在Rails中将实例变量从Model传递到View到Controller

[英]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.nextLesson.previous返回整数而不是课程对象。 如果您想继续使用nextprevious类方法,则可以在视图中进行以下更改

<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM