Search code examples
ruby-on-railslink-to

Controller action doesn't run with link_to function


I need to call a simple controller action through my view using link_to.

In preferences > index.html.erb:

<%= link_to "My link", :controller => 
:preferences, :action => :produces_text %>

Note, I have also tried index.html.erb with this format with no luck:

<%= link_to "My link", {:controller =>
:preferences, :action => :produces_text } %>

In preferences_controller.rb:

def produces_text
  puts "test"
  redirect_to preferences_url
end

In routes:

resources :preferences do
  member do
    get 'produces_text'
  end
end

"test" is not produced in the terminal when I click "My link" and I am not redirected to preferences_url either.


Solution

  • resources :preferences do
        collection do
            get 'produces_text', as: :produces_text
        end
    end
    
    <%= link_to "Link", produces_text_preferences_path %>