如何在评论中实现 acts_as_follower?

How do I implement acts_as_follower in comments?

这里有一些帮助大师:

我想为我的评论实施 acts_as_follower gem。该评论属于post,post有很多评论

我已经让评论可以被用户关注了..

下面是来自 rake 路由的前缀动词、URI 模式和 Controller#action:

post_comment_follows POST

/post/:post_id/comment/:comment_id/follows(.:format) follows_comments#create

post_comment_follow 删除 /posts/:cjob_id/comments/:comment_id/follows/:id(.:format) follows_comments#destroy

我的问题是已经看了很多关于这个的其他文章 eg:file:///C:/Users/c/Desktop/RubyOnRails/ruby%20on%20rails%20-%20acts_as_follower%20for %20multiple%20models%20-%20Stack%20Overflow.html,我已经完成了所有必要的步骤,除了在需要 post id 的评论显示页面上实现它,我尝试了各种显示它的方法,但是它要么说 post (:id) missing 要么 comment (:id) missing。我如何在 post 索引上使用 _comment.html.erb 实现此功能?

首先,代码缩进通常更好

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'

以下returns["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

在您的问题中,您要求“"A B C" OR "A B D"?”但我不确定你在找哪个,也不确定 "C" 或 "D" 是任意的。您可以在 irb 中使用此代码并根据您的用例进行修改。

如果你想 return "A B C" 或 "A B D" 可以使用 Hash#dig 类似的东西:

[].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"]

并且可以根据您的喜好进行更改。