2011-05-30 37 views
10

在routes.rb中引用了一个嵌套的资源编辑路径:生成多个模型

resources :cars do 
    resources :reviews 
end 

resources :motorcycles do 
    resources :reviews 
end 

在ReviewsController:

before_filter :find_parent 

def show 
    @review = Review.find(params[:id]) 
    respond_to do |format| 
    format.html # show.html.erb 
    format.xml { render :xml => @review } 
    end 
end 

def edit 
    @review = Review.find(params[:id]) 
end 

# ... 
def find_parent 
    @parent = nil 
    if params[:car_id] 
    @parent = Car.find(params[:car_id]) 
    elsif params[:motorcycle_id] 
    @parent = Motorcycle.find(params[:motorcycle_id]) 
    end 
end 

生成的“秀”链接,评论简直是(本作品):

= link_to "Show", [@parent, @review] 

同样我想引用审查的通用编辑路径,像(这是行不通的):

= link_to "Edit", [@parent, @review], :action => 'edit' 

有没有人知道这是可能的,或者如果不是,这可能如何实现?

+0

事实证明,我正在寻找能与URL帮手“edit_polymorphic_path”中找到了答案(见:HTTP ://rubydoc.info/docs/rails/3.0.0/ActionDispatch/Routing/PolymorphicRoutes)。为了得到我在上面尝试的链接,我可以用下面的代码完成这个工作:edit_polymorphic_path([@ parent,@review]) – 2011-05-31 00:56:41

回答

16

事实证明,我正在寻找的答案可以在URL助手“edit_polymorphic_path”中找到(请参阅:http://rubydoc.info/github/rails/rails/master/ActionDispatch/Routing/PolymorphicRoutes)。为了得到我试图上面我能有做到这一点的链接:

edit_polymorphic_path([@parent, @review]) 
+0

这已经改变为'edit_polymorphic_path(@parent,@review)'Rails 4 – bibstha 2014-09-25 21:53:24

+0

我不知道Rails 4,但在Rails 5中,您确实需要方括号:edit_polymorphic_path([@ parent,@review]) – 2017-05-04 02:19:27

1

我想你在这里需要的是一个多态关联。 Railscasts.com的Ryan Bates对此进行了完美的解释。

http://railscasts.com/episodes/154-polymorphic-association

它会很容易让你拥有的东西,如:

用户,经理,注意

用户可以有很多的笔记 经理可以有很多的笔记 的注意事项可以属于用户或经理

用户/ 1笔记/编辑 经理/ 1 /笔记/编辑

的Railscast将解释如何做到这一点:)

编辑:

def edit 
    @reviewable= find_reviewable 
    @reviews= @reviewable.reviews 
end 

private 

def find_reviewable 
    params.each do |name, value| 
    if name =~ /(.+)_id$/ 
     return $1.classify.constantize.find(value) 
    end 
    end 
    nil 
end 

然后在你的链接,这将是这样的:

link_to 'Edit Review', edit_review_path([@reviewable, :reviews]) 

^^未经测试。

+0

事实上,我确实与Review模型有多态关联: class Review,belongs_to:reviewsables ,:polymorphic => true class Car,has_many:reviews,:as =>:reviewable class摩托​​车,has_many:评论,:as =>:可复审 因此,与我所做的完全不同的是不幸的是Railscast并没有解决如何获得这种关联的“编辑”路线的问题。 – 2011-05-31 00:36:50

+0

你看过整个Railscast吗?他使用:@commentable = find_commentable 他有find_commentable方法来确定他正在编辑哪个类... – ardavis 2011-05-31 02:05:38

+0

检查我编辑的答案。 – ardavis 2011-05-31 02:08:38

16
link_to 'Edit Review', [:edit, @parent, @review] 
+0

This是超级酷,谢谢!你知道如何得到这样的东西,而不使用“link_to”助手吗? – Abramodj 2013-08-28 20:45:58