Reputation: 2430
I have the following code in my controller:
class TestController < ApplicationController
@@a = 1
def index
@temp = connection.execute("select test_id from mastertest limit #{@@a}, 5;")
end
And I have the following code in my View(Html.erb) File:
<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>
So basically I am trying to change the value of the class variable @@a on clicking the Next button. But it does not change the value of @@aa. Can someone help me how to do that.
Upvotes: 2
Views: 3574
Reputation: 12042
Did you try using helper method?
module ApplicationHelper
@@a = 1
def increment_a
@@a = @@a + 1
end
end
and in your view just call;
<% increment_a %>
Not that the @@ variable is a class variable and it's shared among all instances of the that class. So define that class somewhere in the ApplicationHelper class and then it will be shared and can be accessed in the Controllers and views.
In all cases I highly discourage using class variables in such a way and recommend that you ind another way to share data/variables between view / controller. Maybe use another supporting class or store values in the database.
Upvotes: 3
Reputation: 2430
Ok I managed to fix this:
Ruby has something called a global variable which can be declared like this :
$a = 1
Using $a everywhere retains its value in the controller and the view as well.
Upvotes: 0
Reputation: 9700
If you want to alter a Rails variable on a form submission, you should put the code to do it in the action which processes the form.
As you've written it, I believe the variable will get set when the template containing the form is rendered.
I also vaguely recall that there's some special considerations about class variables in Rails apps. You should look into that and make sure you're using a technique that won't cause any unexpected results.
Upvotes: 0