2010-11-03 42 views
1

我有一個名爲contacts的控制器/模型,我有兩個與聯繫人有多對多關係的其他模型,即:usersfranchises。我一直玩嵌套的路線,我可以讓/用戶/ 1 /聯繫人工作正常,但如果我想要/特許經營/ 1 /聯繫人怎麼辦?有沒有一種動態的方法來解決這個問題?或者我需要做到單個控制器的多條路線

if FRANCHISE 
    <%= link_to "Edit", edit_franchise_contact_path(@contact) %> 
elsif USER 
    <%= link_to "Edit", edit_user_contact_path(@contact) %> 
end 

唯一的其他方法,我可以看到正在使各自的控制器可以處理管理聯繫人的方法。我很感激幫助。

回答

1

怎麼樣多形性網址?

polymorphic_url(record_or_hash_or_array,選擇= {})

Constructs a call to a named RESTful route for the given record and returns the resulting URL string. For example: 

# calls post_url(post) 
polymorphic_url(post) # => "http://example.com/posts/1" 
polymorphic_url([blog, post]) # => "http://example.com/blogs/1/posts/1" 
polymorphic_url([:admin, blog, post]) # => "http://example.com/admin/blogs/1/posts/1" 
polymorphic_url([user, :blog, post]) # => "http://example.com/users/1/blog/posts/1" 
polymorphic_url(Comment) # => "http://example.com/comments" 

你的情況:polymorphic_url([@franchise_or_user, @contact], :action => :edit)

或者乾脆:edit_polymorphic_url([@franchise_or_user, @contact])

參見:http://api.rubyonrails.org/classes/ActionDispatch/Routing/PolymorphicRoutes.html

+0

我試圖如果im in/users/1/contacts有辦法讓它成爲'e dit_polymorphic_url([@ dynamic,@contact])'告訴它它是@user還是@franchise? – rrivas 2010-11-03 19:05:53

+0

你只需將你的對象填充到@dynamic中 - 無論是用戶還是聯繫人。或者你可以檢查設置了哪些參數: 'if params [:user_id]; object_type = User,object_id = params [:user_id]; elsif params [:franchise_id]; ...;結束' – balu 2010-11-03 19:10:18

+0

我正在和它一起玩耍,我得出了和你一樣的結論。非常感謝。我不知道polymorphic_urls存在! – rrivas 2010-11-03 19:12:56