2015-02-10 35 views
0

我目前的項目正在製作一個日記應用程序,用戶可以登錄併發布他們可以鏈接評論的文章。因此,實施該項目的非常自然的方式是一樣的東西如何避免Rails中嵌套的資源

resources :users do 
    resources :articles do 
    resources :comments 
    end 
end 

Class User < ActiveRecord::Base 
    has_many :articles 
end 

Class Article < ActiveRecord::Base 
    belongs_to :user 
    has_many :comments 
end 

Class Comment < ActiveRecord::Base 
    belongs_to :article 
end 

然而,導軌導說的資源不應該被嵌套多個級別。有了這種關係,我該如何避免使用兩級嵌套資源?

+2

導軌指南還告訴您如何避免這種情況。 – 2015-02-10 12:01:21

回答

1

要避免這種情況,您需要使用Shallow Nesting。導軌指南有完整的教程如何做到這一點。還有與此有關的stackoverflow的許多問題。這裏有一些鏈接:

http://guides.rubyonrails.org/routing.html#nested-resources

When using shallow routes, different routes require different form_for arguments

Rails 4 [Best practices] Nested resources and shallow: true

https://railsforum.com/topic/1431-best-practices-nested-resources-and-shallow-true/

如果你仍然得到的任何問題,實現一個,那麼你應該問的計算器。