如何将用户名映射到每条评论

How to map user name to each comment

我有三个不同的模型关联

user.rb

has_many :products
has_many :comments

comment.rb

belongs_to :user
belongs_to :product

Product.rb

has_many :comments
belongs_to :user

def product_comments_object
   comments_object = self.comments.all.select(:id,:user_id,:comment)
   {comments: comments_object}
end

现在,我得到 comments_object 这样的:

"comments": [
  {
    "id": 1,
    "user_id": 1,
    "comment": "comment number 1"
  },
  {
    "id": 2,
    "user_id": 1,
    "comment": "comment number 2"
  }
]

但是如何用 user_name 代替 user_id。我尝试使用 map 但没有帮助我。

您需要解析评论对象以获取用户名。解析每个评论对象并调用 parse_comment 方法,该方法 return 带有用户名的散列。

def product_comments_object
  comments_object = []
  self.comments.each do |comment| 
    comments_object << parse_comment(comment)
  end
  {comments: comments_object}
end

def parse_comment comment
  {id: comment.id, user_name: comment.user.name, comment: "comment number 1"}
end

您可能需要做一点 Ruby 映射。

查看以下内容:

def product_comments_object
   comments = Product.joins(comment: :user).where("products.id is ?", self.id).select("comments.id as id, comments.comment as comment, users.name as name")

   comments_object = map_object(comments)
   {comments: comments_object}
end

def map_object(comments)
   c_o = []
   comments.each do |row|
     c_o << {
       "id" => row.id,
       "name" => row.name,
       "comment" => row.comment
     }
   end
   c_o
end

我认为这应该适合你...

试试这个:

  def product_comments_object
    comments_object = self.comments.all.joins('users')
                          .where('users.id = comments.user_id')
                          .select('comments.id, users.name AS user_name, comments.comment')
    { comments: comments_object }
  end