Search code examples
ruby-on-railscontrollerlink-toput

link_to using PUT method syntax to a different controller in rails 3


I try to call an action of my Gallery controller from a Portfolio view. A Portfolio is made of many galleries.

I try this:

<%= link_to("Heart", gallery_path(gallery), :action => "like", :method => :put ,  :remote => true) %>

<%= link_to("Heart", :controller => :galleries, :action => "like", :method => :put ,  :remote => true) %>

And I obtain:

<a href="/galleries/3" action="like" data-method="put" data-remote="true" rel="nofollow">Heart</a>

and

<a href="/galleries/1/like?method=put" data-remote="true">Heart</a>

I want to get but i m stuck...:

<a href="/galleries/3/like" data-method="put" data-remote="true">Heart</a>

Any RAILS God to help me ?


Solution

  • I believe you're getting behaviour because you're trying to use the "path helper" and "params hash" styles in the same link_to (see the docs for more details). I prefer the path helper style, so I'd write the link like this:

    <%= link_to(
        'Heart',
        like_gallery_path(gallery),
        {:method => :put, :remote => true}
    ) %>
    

    If you like the params hash style, you'd write:

    <%= link_to(
        'Heart',
        {:controller => 'galleries', :action => 'like', :id => gallery.id},
        {:method => :put, :remote => true}
    ) %>
    

    Note that the URL parameters (controller, action, etc.) are in a separate hash from the link parameters (method & remote).

    Hope that helps!