2011-05-30 75 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