2011-09-16 27 views
0

兩個集合,我打算到一些分頁添加一對夫婦在我的應用模型,我覺得我在這裏失去了一個關鍵概念。這裏是我的應用程序:分頁上的同型號

class Gallery < ActiveRecord::Base 

    has_many :photos 
    has_many :comments 

end 

class GalleryController < ApplicationController 

    def show 
     # some process here 
     @gallery = Gallery.find(params[:id]) 
    end 

end 

我想能夠獨立分頁照片和評論我給出的給定的畫廊。我需要用AJAX做這件事,我有一種感覺,用照片或畫廊的參數來調用'show'是矯枉過正的(即,如果我只是在尋找照片或評論,爲什麼我需要找到畫廊)。

我應該如何設計這個功能嗎?

什麼是替代這裏呼籲GalleryController.show?

回答

0

我設置它是這樣的:

class GalleriesController < ApplicationController 
    def index 
    @galleries = Gallery.paginate(params) 
    end 
end 

class CommentsController < ApplicationController 
    def index 
    @comments = parent.comments.paginate(params) 
    end 

    def parent 
    @parent ||= Gallery.find(params[:gallery_id]) 
    end 
end 

class PhotosController < ApplicationController 
    def index 
    @photos = parent.photos.paginate(params) 
    end 

    def parent 
    @parent ||= Gallery.find(params[:gallery_id]) 
    end 
end 

# config/routes.rb 
resources :galleries do 
    resources :photos 
    resources :comments 
end 

然後你只需要求:

/galleries/1/comments 
/galleries/1/photos 

時退房inherited_resources寶石此嵌套模型模式。

但最好你想爲這一切在一個請求。檢查出this post on the Presenter Pattern in Rails

希望有所幫助。

0

是的,我絕對推薦使用inherited_resources,因爲它可以節省你很多的樣板代碼。剛剛成立由viatropos描述的這些資源,增加JSON應答(與inherited_resources,它的那麼容易,因爲添加respond_to :json, :html到控制器)。然後在ajax端使用誘人的插件,如jquery.tmplmustache.js或其他,爲每個資源預渲染一個項目模板,然後使用ajax檢索您的分頁數據爲JSON並將其渲染到您的模板中。這非常容易,但如果你需要一步一步的指導,請問。