Ruby on Rails - Path variable without using resources route

时间:2015-12-10 01:44:38

标签: ruby-on-rails ruby hyperlink path routes

I have a controller, let's just call it FruitsController, that grabs all of the fruit and sends it to the index view. In the view, I want to show links to the individual pages for those fruits. I'm using the format:

<% @fruits.each do |fruit| %>
    <%= link_to fruit.name, fruit_path(fruit) %>       
<% end %>

And this works great when I have the route resources :fruits, but I don't want routes for deleting, saving, and updating, so I don't want to use resources. But when I just do individual routes for showing all and individual fruits, I get the error fruit_path function is not defined, and when I use the function fruits_path it works but it just appends a period to the path like /fruits.1. How can I use the fruit_path function without using resources? Thanks.

2 个答案:

答案 0 :(得分:6)

There are a number of ways you could do this; in your config/routes.rb, any of the following should work:

resources :fruits, only: :show

resources :fruits, except: [:index, :edit, :destroy, :update] # etc

get 'fruits/:id', to: 'fruits#show', as: :fruit

scope controller: :fruits do
    get 'fruits/:id' => :show, as: :fruit
end

答案 1 :(得分:3)

您不仅限于资源,还可以自定义和创建自己的路径,例如:

获取'/:用户名/照片',以:'用户#show',如:'collage'   
to:表示控制器/动作,在这种情况下,用户是控制器,show是动作。   
as:为你创建一个路径'collage_path'

您可以找到有关路由=&gt; http://guides.rubyonrails.org/routing.html

的详细信息