2016-07-29 73 views
-1

這裏有一些幫助大師:如何在評論中實施acts_as_follower?

我想實施acts_as_follower gem爲我的評論。評論屬於帖子和帖子有很多評論。

我已經得到用戶的評論隨動..

而這些前綴動詞,URI模式和控制器#行動從下面耙路線:

post_comment_follows POST

/後/: POST_ID /評論/:COMMENT_ID /如下(:格式)follows_comments#創建

post_comment_follow DELETE /posts/:cjob_id/comments/:comment_id/follows/:id(.:format)follows_comments#破壞

我的問題是通過了很多其他文章,例如:file:/// C:/ Users/c/Desktop/RubyOnRails/ruby​​%20on%20rails%20-%20acts_as_follower%20for%20multiple%20models %20-%20Stack%20Overflow.html,我已經完成了所有必要的步驟,除了在需要帖子ID的評論展示頁面上實現它之外,我嘗試了顯示它的各種方法,但它或者說post(:id)缺失或評論(:id)缺失。如何在後期索引中使用_comment.html.erb實現此功能?

+0

哦,這是一個程序員的笑話大聲笑... – Dlaw

+0

順便說一句,你必須缺少一些括號。 –

+0

謝謝你的觀察。我已糾正它。 – Dlaw

回答

0

下返回["A", "B", "C", "D"]

#for trying out in `irb` this is fine, but I would recommend refactoring to smaller methods 
[].tap do |result| 
    result << arry[0].keys 
    second_level_hash_names = arry.map {|hash| hash.values.map {|values_hash| values_hash["name"]}}.flatten 
    third_level_hash_names = arry.map {|hash| hash.values.map {|values_hash| values_hash["sub"].map {|sub_hash| sub_hash["name"]}}}.flatten 
    result << second_level_hash_names << third_level_hash_names 
end.flatten 

在你你問「ABC」還是「ABD」?但我不確定你在找什麼,以及「C」還是「D」是任意的。您可以在irb中使用此代碼進行遊戲並修改您的用例。

0

首先,它通常是更好地縮進代碼

arry =[ 
    {"A"=>{ 
    "name"=>"B", 
    "id"=>1, 
    "sub"=>[ 
     { 
     "name"=>"C", 
     "id"=>1 
     },{ 
     "name"=>"D", 
     "id"=>2 
     } 
    } 
    ] 

然後你看你需要做什麼:

arry[0]['A']['sub'][0]['name'] # => 'C' 
arry[0]['A']['sub'][1]['name'] # => 'D' 
+0

謝謝,但我已經嘗試過這樣的東西......我需要的是打印出三個....像「A B C」。 – Dlaw

0

如果你想回到 「A B C」 或 「A B d」 可以做到使用散列#掏一樣的東西:

[].tap do |result| 
    result << arry[0].keys 
    result << arry[0].flatten.dig(1, "name") 
    result << arry[0].flatten.dig(1, "sub", 1, "name") 
end.flatten 

輸出:

["A", "B", "D"] 

,可以作爲你的喜好改變。

+0

未定義的方法'挖掘'......... MethodError ...這就是我所得到的。我不知道爲什麼。 – Dlaw

+0

未定義的方法'挖'爲......... MethodError ...這就是我所得到的。我不知道爲什麼。 – Dlaw

+0

@Dlaw,僅適用於2.3版本的Ruby – nathanjo