0

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
dblarons
  • 123
  • 2
  • 11

1 Answers1

2
resources :preferences do
    collection do
        get 'produces_text', as: :produces_text
    end
end

<%= link_to "Link", produces_text_preferences_path %>
Robin
  • 21,667
  • 10
  • 62
  • 85
  • WOW! You are the best! So, it turns out the collection part is the one making the difference. What is the difference between collection and member? I will accept your answer in 1 minute! – dblarons Mar 09 '13 at 01:17
  • Member will act on a single preference, i.e., `preferences/1/produces_text`. Collection acts on the collection, i.e., `preferences/produces_text` – Logan Serman Mar 09 '13 at 01:21
  • So, for instance, if I wanted to pass a image_id within a link_to tag, I would need to do member? – dblarons Mar 09 '13 at 01:23
  • No, you wouldn't necessarily. What are you trying to do exactly? As much as possible, you should think in terms of resources to design your restful routes. – Robin Mar 09 '13 at 03:05
  • How should I pass an image_id from the view to the controller? I tried adding :image_id => 3 to the view and then puts params[:image_id] in the controller, but the params[:image_id] is nil. – dblarons Mar 09 '13 at 05:07
  • `produces_text_preferences_path(image_id: 1)`, and you should be able to access it in the controller. Take the habit of looking at the logs to see what's going on with your params. – Robin Mar 09 '13 at 05:42
  • I ended up using console to access the params and check how they are being valued. Thanks for your help! – dblarons Mar 09 '13 at 17:47