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

时间:2015-11-04 09:00:41

标签: sql ruby-on-rails model associations

我有三种不同的关联模型

user.rb

<receiver android:name="xxx.xxxx.xxxx.Receiver1"
            android:enabled="true"
            android:exported="true"
            android:permission="xxx.xxxx.permission.API">
            <intent-filter>
                <action android:name="xxx.xxxx.permission.API.1" />
            </intent-filter>
</receiver>

comment.rb

RESULT_CANCELLED

Product.rb

has_many :products
has_many :comments

现在,我得到的是belongs_to :user belongs_to :product

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,但没有帮助我。

3 个答案:

答案 0 :(得分:2)

您需要解析评论对象以获取用户名。解析每个注释对象并调用返回带有用户名的哈希的parse_comment方法。

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

答案 1 :(得分:1)

您可能需要进行一些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

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

答案 2 :(得分:1)

试试这个:

  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