saskcan saskcan - 1 year ago 92
Ruby Question

rails link_to with block, controller options and html post

I am trying to use link_to in rails 4 with controller and html options and a do..end block. I have seen similar posts but have not been able to use any of the answers successfully.

Working code without a do..end block:

<%= link_to 'recommend', { controller: 'recommendations', id: }, method: :post %>

When I try to use some embedded ruby to add extra information to the link, I cannot get it to work:

<%= link_to( { controller: 'recommendations', id: }, method: :post) do %>
<p>Some Html</p><%= offer.recommendations %>
<% end %>

The code compiles but in the rendered, the link that is generated is the following:

<a controller="recommendations" id="38">
<p>Some Html</p>0

Any help would be appreciated. I think that it is a small problem with the syntax but I have tried all manner of brackets, spaces etc that I could think of without luck.

UPDATE: I have tried the following code without success:

<%= link_to( { controller: 'recommendations', action: 'create', id: }, method: :post) do %>
<p>Some Html</p><%= offer.recommendations %>
<% end %>

The HTML output is:

<a action="create" controller="recommendations" id="39">
<p>Some Html</p>0

This might not be important but as a side note, the create action doesn't have a helper function for links. When I run the

rake routes

command I get the following

recommendations GET /recommendations(.:format) recommendations#index
POST /recommendations(.:format) recommendations#create
new_recommendation GET /recommendations/new(.:format) recommendations#new

In my opinion this isn't a problem but it is a reason why code such as:

link_to create_recommendation_path

won't work. Finally, the intention of the link is to act as a 'like' button. It creates a recommendation and then displays the current page again. Once again, thanks for the help in advance.

Answer Source

The reason link_to create_recommendation_path doesn't work is because there is no named route for create_recommendation_path, only for recommendations_path. You can see the named routes in your routes list (which you have in your post above). The left most column that comes out of routes shows the named routes. Notice that recommendations#create doesn't have an entry in the list.

You could probably get the path you want with

<%= link_to recommendations_path(:offer_id =>, :method => :post do %>
    html stuff
<% end %>

This should post to a path that looks like

/recommendations?offer_id=<the offer id>

(except the post data will be in the headers not on the URL) This will work if the create method going to do something like


and the only parameter you need to create a new Recommendation is an offer_id

What I don't understand is why you're trying to POST with a link? Does creating a recommendation only require an offer id?