0

The @test variable I have is getting evaluated before I want it to. Here's what I intend: I have a button (link right now) with a variable shown next to it. The value should say "blank" when the page is initially loaded. When I click that button, the page should refresh and the variable should be changed to something else because the button calls a helper method.

Here's what I have in home.html.erb:

<%= link_to 'Do stuff', my_helper_method(), :method => :get %>
<%= @test %>

Here's what I have in my_proj_helper.rb (helper method):

module MyProjHelper
    def my_helper_method()
       @test = "changed"
    end
end

In my_proj_controller.rb (controller), I have this:

class My_Proj_Controller < ApplicationController
    def home
        @test = "blank"
    end
end

I must not be doing things correctly. What needs to change?

Jack
  • 5,264
  • 7
  • 34
  • 43

2 Answers2

1

You cannot use a helper method like that. Here's what you can do:

Create a route in routes.rb

   get '/some_path/:test_variable' => 'my_proj_controller#test_action', as: :test_action

Then create a corresponding action in your controller

   def test_action
     @test = params[:test_variable]
     render 'home'
   end

Then change the link

    <%= link_to 'Link', test_action_path('change') %>

What it does when user clicks the link is it sends a GET request from your page to My_Proj_Controller with a test_variable parameter in it. Your controller receives the request, sets @test variable and renders the home.html.erb page then.

JazzJackrabbit
  • 515
  • 2
  • 10
0

I think you're trying to hit the helper method when you click. This isn't what helper methods are for - they simply do something that you need in a view or controller - like render html. The 'link_to' method is a helper, for example. If you want the @test variable to change as you want - just set the value in the controller conditionally.

The second param of the link_to method is supposed to be the url that you are tring to navigate to. If it's a method, it should return a string. In this case, you call a method that does return a string. If you look in the a href="" of that tag, you'll see "changed" as the href attribute.

Mark Swardstrom
  • 17,217
  • 6
  • 62
  • 70