gpt4 book ai didi

ruby-on-rails - rails 3路线: DRY members

转载 作者:行者123 更新时间:2023-12-03 00:48:48 25 4
gpt4 key购买 nike

我需要将以下成员方法添加到多个资源中,有没有办法将其干燥?

 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

最佳答案

你不能在路由文件中定义一个方法吗?

def foo
member do
get :votes
post :up_vote
post :down_vote
end
end


resources :news do
resources :comments do
foo
end
end

编辑

我以前没有使用过这种技术。当我做“rake 路线”时,它似乎起作用了。无论如何,路由文件只是 Ruby 代码。请注意您定义的方法的名称,因为它是在 ActionDispatch::Routing::Mapper 的实例中定义的。

# routes.rb

MyApp::Application.routes.draw do
puts self
puts y self.methods.sort
end

# Terminal
> rake routes

关于ruby-on-rails - rails 3路线: DRY members,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4262988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com