Rails 3 路线:DRY 成员
我需要将以下成员方法添加到许多资源中,有没有办法将其干燥?
member do
get :votes
post :up_vote
post :down_vote
end
在我的routes.rb
resources :news do
resources :comments do
member do
get :votes
post :up_vote
post :down_vote
end
end
end
resources :downloads do
resources :whatever do
member do
get :votes
post :up_vote
post :down_vote
end
end
end
编辑
中,我实际上已将其移至模块中,如下所示:
module Votable
module RoutingMethods
def votable_resources
member do
get "up_votes"
get "down_votes"
post "up_vote"
post "down_vote"
end
end
end # RoutingMethods
end
现在,我的routes.rb如下所示:
require 'votable'
include Votable::RoutingMethods
MyApp::Application.routes.draw do
namespace :main, :path => "/" do
resources :users do
resources :comments do
votable_resources
end
end
end
end
请参阅我的内联注释,但我希望命名的路线看起来像:main_users_comments_up_votes
I need to add the following member methods to a number of resources, is there a way to DRY this up?
member do
get :votes
post :up_vote
post :down_vote
end
In my routes.rb
resources :news do
resources :comments do
member do
get :votes
post :up_vote
post :down_vote
end
end
end
resources :downloads do
resources :whatever do
member do
get :votes
post :up_vote
post :down_vote
end
end
end
EDIT
I've actually moved it out into a module like so:
module Votable
module RoutingMethods
def votable_resources
member do
get "up_votes"
get "down_votes"
post "up_vote"
post "down_vote"
end
end
end # RoutingMethods
end
Now, my routes.rb looks like this:
require 'votable'
include Votable::RoutingMethods
MyApp::Application.routes.draw do
namespace :main, :path => "/" do
resources :users do
resources :comments do
votable_resources
end
end
end
end
See my inline comments, but I want the named route to look like: main_users_comments_up_votes
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能在你的路由文件中定义一个方法吗?
编辑
我以前没有使用过这种技术。当我做“耙路线”时,它似乎起作用了。无论如何,路由文件只是 Ruby 代码。请注意您定义的方法的名称,因为它是在 ActionDispatch::Routing::Mapper 的实例中定义的。
Can't you just define a method in your routes files?
Edit
I haven't used this technique before. It just seemed to work when I did 'rake routes'. Anyways, the routes file is just Ruby code. Just be careful about the name of the method you define because it's defined in the instance of ActionDispatch::Routing::Mapper.