2009-10-02 111 views
1

我在做什么:是否可以将自定义路径追加到Rails路由的“新”路径?

我正在建立一个系统,其中有不同类型的帖子。撇开车型,这个问题是关于路线和控制器

基本上/posts/new应该去各种各样的索引页,而/posts/new/anything要查找的类型anything再建一个表单创建一个新的。

如何我试图做到这一点:

随意忽略这一部分,因为我可以在错误的轨道上完全。

在路由配置:

map.connect '/posts/new', :controller => 'posts', :action => 'new_index' 
map.resources :posts, :path_names => { :new => 'new/:type' } 

在控制器:

class PostsController 
    # implicit: def new_index ; end 

    def new 
    @post = class_for_type(params[:type]).new 
    end 
end 

视图有代码看起来在@post来确定哪组的观点使用的类型。事实证明,这使我获得了90%的途径:/posts/new/quip实际上确实将我发送到正确的页面以创建一个提示,等等。 /posts/new确实将我发送到索引页面。

问题是双重的。

  1. 我还是希望有便捷的方法是这样的:

    <%= link_to 'New Post', new_post_path %> 
    

    但这现在是无效的new_post_path需要:type参数。

  2. 我想尽可能使用一条路线。

+0

这是更好地说,而不是“路径”路线' – khelll 2009-10-02 11:30:31

+0

不,路线则是另一个概念链接到控制器,动作,而params的路径。 – Trejkaz 2009-10-03 08:55:25

回答

3

彼得Wagenet的解决方案给了我缺少一块拼图(:type => nil),它可以让我做一个行:

map.resources :posts, :path_names => { :new => 'new/:type' }, 
       :requirements => { :type => nil } 

当然,我仍然不得不进入控制器并进行修复使它会从:new操作中呈现new_index.html.erb

(好吧,我想这不是一条线了。)

new_post_path      # => '/posts/new/' 
new_post_path(:type => 'quip') # => '/posts/new/quip' 
new_post_path('quip')    # => '/posts/new/quip' 
0

我想你应该看看Rails的单表继承: http://juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/

那会做了很多更轻松地管理您的文章类型,你有很多车型继承了全球一个,但基于相同的SQL基础。

为了您自己的问题,为什么不重新定义new_post_path帮助器方法? 是这样的:

def new_post_path 
    { :controller => 'posts', :action => 'new', :type => params[:type] } 
end 

类型是现在自动基于参数数组上给出。

+0

(1)我已经在使用STI。就像我说的那样,这个模型与这个问题的目的无关。 (2)链接到new_post_path用于布局(它在每个页面上),因此params [:type]可能不存在。因此,当你在这样一个页面上时,我想显示一个索引页面。确实,我可以重新定义帮助者,尽管我猜想只返回'/ posts/new'。 – Trejkaz 2009-10-03 08:57:48

+0

我应该补充说,我现有的两线解决方案的主要问题在于它很冒险。如果我再添加3行黑客来解决它,那么它会变成4行黑客,如果我知道如何按照我的意愿去做,它可能是1行路线。 – Trejkaz 2009-10-03 08:59:33

2

如果你能分享的行动生活,那么你可以设置如下:

# Routes 
map.new_person '/people/new/:type', :controller => :people, :action => :new, :type => nil 
map.resources :people, :except => [:new] 

# Controller 
class PeopleController < ApplicationController 

    def new 
    unless params[:type] 
     render :action => :new_index and return 
    end 

    @post = class_for_type(params[:type]).new 
    end 

end 

这可以让你保持默认格式的单一路线,以及指定的能力类型:

new_person_path      # => /people/new/ 
new_person_path(:type => 'anything') # => /people/new/anything 
new_person_path(:employee)   # => /people/new/employee