2015-05-24 16 views
0

我有3個模型作爲類別,帖子和評論。我想在類別頁面中顯示帖子和評論數量。如何從控制器傳遞不同的參數?

category.(:id)Post.(:id).comments.count將返回評論的數量。

但是,我應該如何從類別控制器傳遞這些參數?我也試圖寫同樣的jbuilder視圖。

或者我可以直接從jbuilder視圖做這樣的事情嗎?

#this work 
 

 
json.number @category.posts.count 
 

 
#this one doesn't work 
 

 
json.number @category.posts.comments.count

回答

1

json.number @category.posts.count它的工作原理,但 json.number @category.posts.comments.count這不。

您可以在導軌控制檯中測試..如@category.posts.comments.count。 它可能會引發錯誤,如
NoMethodError: undefined method 'comments' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Post:0x0000000920b058>

這是因爲@category.posts返回集合不Post對象。

一個可能的解決方案是
@category.posts.map {|post| [post, post.comments.count] } 這給你的陣列每帖子的評論總數。這可能不是您想要的,但您可以修改以符合您的要求。

+0

您的解決方案將提供總數量的評論,我想分別獲取每個帖子的評論數量。 我想要建立的是一個'category.json.jbuilder'文件,它提供了每個帖子及其屬性的集合,我也想包括每個帖子的編號。 – user121212

+0

@ user121212我編輯了答案。看看它是否有幫助 – illusionist

1

從控制器至你要使用@(實例變量)以呈現視圖傳遞參數最簡單的方法。因此,您可以通過:

@count = <your code above> 
@all_posts = <your post code> 

如果你有很多不同的參數,只需要創建一個對象通過他們橫跨:

@post_info = { 
     count: <your code above>, 
     all_posts: <your post code> 
} 

,然後使用@post_info在你看來檢索它們[:計數]和@post_info [:all_posts]

+0

問題是,我只能訪問類別控制器中的category_id。 – user121212

相關問題