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.

1 Answer 1

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

<%= link_to "Link", produces_text_preferences_path %>
Sign up to request clarification or add additional context in comments.

7 Comments

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!
Member will act on a single preference, i.e., preferences/1/produces_text. Collection acts on the collection, i.e., preferences/produces_text
So, for instance, if I wanted to pass a image_id within a link_to tag, I would need to do member?
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.
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.