Francis Chartrand
Francis Chartrand

Reputation: 167

Ruby on Rails, `link_to` with `image_tag` talk to a controller

Hi I'm currently learning Ruby On Rails and I have a little mistake.

I want to add a hyperlink on my image and when I click on this image I want to talk to my function 'add_to_cart'. Right now it's currently working with button_add but not with the function link_to.

My link_to code:

<%= link_to image_tag(product.image_url, :alt => product.title, :width => 100, :border => 1), :id => product, :action => 'add_to_cart' %>

The error:

Unknown action

The action 'show' could not be found for StoreController

Hyperlink HTML:

<a href="/store/2">
   <img width="100" border="1" src="/assets/images/cover_test.jpg" alt="Book 2">
</a>

Thanks You for your help :)!

------ SOLUTION ------

I can't answer my question but I found the solution. I had a problem with my route.rb configuration, it's was creating a conflict with my function index.

Old route.rb config:

match 'store/:id', :to => 'store#add_to_cart'

New route.rb config:

match 'store/add_to_cart/:id', :to => 'store#add_to_cart'

Here's my link_to code:

<%= link_to image_tag(product.image_url, :alt => product.title, :width => 100, :border => 1), {:action => 'add_to_cart', :id => product} %>

Thank You @Justin for your help :).

Upvotes: 0

Views: 1890

Answers (3)

Francis Chartrand
Francis Chartrand

Reputation: 167

I found the solution. I had a problem with my route.rb configuration, it's was creating a conflicts with my function index.

Old route.rb config:

match 'store/:id', :to => 'store#add_to_cart'

New route.rb config:

match 'store/add_to_cart/:id', :to => 'store#add_to_cart'

Here's my link_to code:

<%= link_to image_tag(product.image_url, :alt => product.title, :width => 100, :border => 1), {:action => 'add_to_cart', :id => product} %>

Upvotes: 0

Richie Min
Richie Min

Reputation: 654

link_to(body, url_options = {}, html_options = {})
# url_options, except :confirm or :method,
# is passed to url_for

the second parameters is about url options, and the third parameters is about html options

learn how to lookup api document and it will avoid this kind of mistake

Upvotes: 0

Justin Rhyne
Justin Rhyne

Reputation: 217

try something like this?

<%= link_to image_tag(product.image_url, :alt => product.title, :width => 100, :border => 1), {:controller => 'your_controller', :action => 'add_to_cart', :id => product} %>

(not tested)

Upvotes: 1

Related Questions