2012-01-17 90 views
1

因此,我正在開發一個新的rails項目,它涉及從單個rails安裝中運行多個網站。我對如何在不嵌套資源的情況下進行關聯感到困惑。Rails 3多站點(與id的關聯)?

注:我使用的子域網址這樣會site1.ex.com/photos, site2.ex.com/ramps

比如現在我有一個網站叫網站1網站1有照片,視頻和坡道。我可以通過告訴rails site has_many來做這個關聯:photos,:videos,:ramps(代碼沒有正確格式化,只是給了你這個想法)。一切工作正常,包括網址,但這是我的問題。

  1. 網站是包含在我不想要的網址(例如example.com/sites/1/photos)。
  2. 協會工作正常,但如果我想爲這3件物品的父母呢? Rails建議你不要在1層以上嵌套路由。 enter image description here

這裏是我想要做的 enter image description here

  1. 我怎樣才能叫網站之間的關聯,而無需使用嵌套資源(不能捕捉album_id照片的SITE_ID)是什麼?
  2. 如果專輯has_many:照片belongs_to:site我該如何在我的控制器(任何示例)中調用?

因爲我添加了照片,所以有人可以理解我想要完成什麼。

回答

1

如果您使用子域名,則不必爲sites使用嵌套資源。要找到一個網站:

class ApplicationController < ActionController::Base 

    before_filter :find_site_by_subdomain 

    def find_site_by_subdomain 
    @site = Site.find_by_subdomain!(request.subdomain) 
    end 

end 

對於所有其他資源,你巢他們不是在Site而是以自己爲父母(相冊/照片,視頻,坡道)。而在你AlbumsController你只想要那些屬於當前子域名的網站,讓你利用你的before_filter從ApplicationController和使用@site對象:

class AlbumsController < ApplicationController 

    … 

    def show 
    @album = @site.albums.find(params[:id]) 
    end 

    … 
end 
+0

如果什麼專輯'的has_many:photos'如何我可以將專輯,網站和照片集成到一個電話或我的控制器中嗎? – coletrain 2012-01-17 16:00:39

+1

製作一個PhotosController,添加'before_filter:find_album'並製作一個名爲'find_album'的方法,在其中調用'@album = @ site.albums.find(params [:album_id])''。然後在你的show方法中,你可以調用'@photo = @ album.photos.find(params [:id])'' – 2012-01-17 19:39:32