简体   繁体   English

在Rails中将URL传递给link_to的默认方式

[英]Default way for passing a URL to link_to in Rails

This is a very basic question with probably an easy answer. 这是一个非常基本的问题,可能很容易回答。 Let's say I have a model called Product. 假设我有一个称为Product的模型。 When I add 当我添加

map.resources :products

to my routes.rb I have access to some default paths new_product_path, edit_product_path and so on. 到我的routes.rb,我可以访问一些默认路径new_product_path,edit_product_path等。 As I understand this should be used when linking to a resource eg using the link_to helper method: 据我了解,在链接到资源时应使用此方法,例如使用link_to helper方法:

link_to "Edit Product", edit_product_path(@product)

My question is: What do I do when I have other controller methods like for example 我的问题是:当我有其他控制器方法(例如)时该怎么办

def do_something
  ...
end

What's the "best" way to link to this controller method? 链接到该控制器方法的“最佳”方法是什么?

link_to "Do Something", {:controller => 'products', :action => 'do_something', :id => @product.id}

for sure would work. 当然可以。 But is that what I should use? 但这是我应该使用的吗?

I hope I made my point clear! 希望我说清楚! Please comment if not. 如果没有,请发表评论。 I'll try to explain it better then. 那我会尽力解释。

You might want to read up on the Rails Routing, specifically, adding a new Restful route . 您可能需要阅读Rails路由,特别是添加新的Restful路由

If you use this method, I believe it is fairly simple: 如果您使用此方法,我相信它相当简单:

# routes.rb
map.resources :products, :member => { :do_something => :get }

# your view.rb file
link_to "Do Something", do_something_product_path(object_id)

Also make sure you read the section regarding "collection routes" if you want the URL to operate on all of the products (like a more complex index page). 如果您希望URL在所有产品上都可以使用(例如更复杂的索引页),还请确保阅读有关“收集路线”的部分。

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

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