简体   繁体   English

Ruby on Rails,带有“ image_tag”的“ link_to”与控制器对话

[英]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. 嗨,我目前正在学习Ruby On Rails,但我有一个小错误。

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' . 我想在图像上添加超链接,当我单击该图像时, 我想和我的函数'add_to_cart'对话 Right now it's currently working with button_add but not with the function link_to . 现在,它当前正在与button_add一起使用,但与link_to函数一起使用。

My link_to code: 我的link_to代码:

<%= 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: 超链接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. 我的route.rb配置有问题,它正在与我的函数索引冲突。

Old route.rb config: 旧的route.rb配置:

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

New route.rb config: 新的route.rb配置:

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

Here's my link_to code: 这是我的link_to代码:

<%= 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 :). 谢谢@Justin的帮助:)。

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) (未测试)

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 第二个参数与url选项有关,第三个参数与html选项有关

learn how to lookup api document and it will avoid this kind of mistake 了解如何查找api文档,它将避免这种错误

I found the solution. 我找到了解决方案。 I had a problem with my route.rb configuration, it's was creating a conflicts with my function index. 我的route.rb配置有问题,它正在与我的函数索引冲突。

Old route.rb config: 旧的route.rb配置:

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

New route.rb config: 新的route.rb配置:

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

Here's my link_to code: 这是我的link_to代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM