How to define a custom path in rails?

六月ゝ 毕业季﹏ 提交于 2019-12-21 04:14:19

问题


I have a User model. If I do:

def my_action
  @user = User.new
end

then

  <% form_for(@user) do |f| %>

I get

undefined method `users_path' for #<ActionView::Base:0x1b4b878>

Which make sense because I haven't mapped it going map.resources :users... but I don't want to do it this way because I don't need all the resources.

How can I just define this user_path method in my routes?


回答1:


You can also customize restful routes. For example in my application only the index and show actions are appropriate for certain controllers. In my routes.rb file I have some routes like this:

map.resources :announcements, :only => [:index, :show]

You can also use :except if that's more appropriate.




回答2:


Since I came here looking for a way to create helpers in routes.rb, here is the way to do it:

get '/users/:id/' =>'users#show', :as => :user



回答3:


You can map custom routes in your routes.rb file like this...

map.users '/users', :controller => 'user', :action => 'index'

This gives you the users_path helper you're looking for.



来源:https://stackoverflow.com/questions/1436309/how-to-define-a-custom-path-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!