如何在评论中实现acts_as_follower?

时间:2016-07-29 01:09:42

标签: ruby-on-rails rubygems comments

这里的一些帮助大师:

我想为我的评论实现acts_as_follower gem。评论属于帖子和帖子有很多评论。

我已经让用户发表了评论..

以下是rake路线的前缀动词,URI模式和控制器#动作:

post_comment_follows POST

/ post /:post_id / comment /:comment_id / follow(。:format)following_comments #create

post_comment_follow DELETE /posts/:cjob_id/comments/:comment_id/follows/:id(.:format)follow_comments#destroy

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

在post index上实现此功能

3 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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

在你的问题中,你要求“”A B C“或”A B D“?”但我不确定你在找什么,以及“C”或“D”是否是任意的。您可以在irb中使用此代码并根据您的使用情况进行修改。

答案 2 :(得分: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"]

可以根据自己的喜好进行更改。

相关问题