2014-06-14 43 views
0

我創建了一個「文章」腳手架,並使用devise設置了用戶身份驗證。 我想創建一個顯示特定用戶所有文章的頁面!創建一個頁面以顯示特定用戶創建的內容

在我的文章索引列出了所有文章和創建它的用戶的名稱,我希望其他人能夠點擊此用戶的名稱並訪問此頁面顯示此用戶創建的其他文章!

非常感謝,我最近開始使用rails,並且嘗試了很多方法來完成它,但我無法弄清楚這一點!

回答

2

那麼你想要的是屬於用戶的所有文章。

在你的用戶模型中添加;

has_many :articles 

並在文章模型中添加;

belongs_to :user 

創建一個返回該用戶所擁有的所有文章這樣

@user_articles = User.find(user_id).articles 
0

我想創建一個頁面一個頁面,顯示由特定 用戶創建的所有物品!

-

嵌套資源

要做到這一點,你通常會是最好的使用nested resource(如識別父對象),但是當你正在使用devise,我們有current_user助手可用(意思是我們可以自然地使用控制器)

如果您要使用nested resources方法,您可以這樣做:

#config/routes.rb 
resources :users do 
    resources :articles #-> domain.com/users/:user_id/articles/ 
end 

這將允許你調用articles#index方法在articles控制器:

#app/controllers/articles_controller.rb 
def index 
    user = User.find params[:user_id] 
    @articles = user.articles 
end 

這,當然,考慮到協會是acacia建議:

#app/models/user.rb 
Class User < ActiveRecord::Base 
    has_many :articles 
end 

#app/models/article.rb 
Class Article < ActiveRecord::Base 
    belongs_to :user 
end 

-

curre nt_user

current_user是設計

創造了一個幫手這意味着你不需要使用嵌套的資源,你手頭上已經有在user對象。我會這樣做:

#config/routes.rb 
resources :articles #-> domain.com/articles 

#app/controllers/articles_controller.rb 
Class Articles < ApplicationController 
    def index 
     @articles = current_user.articles 
    end 
end 
相關問題