我的 Controller 中有以下代码:
class TestController < ApplicationController
@@a = 1
def index
@temp = connection.execute("select test_id from mastertest limit #{@@a}, 5;")
end
我的 View (Html.erb)文件中有以下代码:
<button type="submit" value="Next" form="submit_form">NEXT</button>
<form id="submit_form">
<% @@a = @@a + 1 %>
<table>
<% @temp.each do |row| %>
<tr><td><%= row[0] %></td></tr>
<% end %>
</table>
</form>
所以基本上我试图在单击“下一步”按钮时更改类变量@@a 的值。但它不会改变@@aa的值。有人可以帮我怎么做吗?
最佳答案
您尝试过使用辅助方法吗?
module ApplicationHelper
@@a = 1
def increment_a
@@a = @@a + 1
end
end
在你看来,只需调用即可;
<% increment_a %>
@@ 变量并不是一个类变量,它在该类的所有实例之间共享。因此,在 ApplicationHelper 类中的某个位置定义该类,然后它将被共享并可以在 Controller 和 View 中访问。
在所有情况下,我强烈反对以这种方式使用类变量,并建议您找到另一种在 View / Controller 之间共享数据/变量的方法。也许使用另一个支持类或将值存储在数据库中。
关于html - 更改 Html.erb 中 Ruby 变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13146035/