如何从表和关联表返回特定列

时间:2019-08-05 16:22:52

标签: ruby-on-rails-5 associations

我有两个模型:

class Comment < ApplicationRecord
  belongs_to :user
  has_many :comments, class_name: 'Comment', foreign_key: 
  'comment_id'
 end

=> Comment(id: integer, text: string, user_id: integer, product_id: 
integer, created_at: datetime, updated_at: datetime, comment_id: 
integer)

class User < ApplicationRecord
  self.table_name = 'users'
  has_many :comments
end

=> User(id: integer, username: string)

如何返回textusername注释对象。

例如c = Comment.limit(2) => c.map { |a| hash << c.text, hash << c.user['username']}。我想为每个评论返回评论文本和用户名。告诉我你是否不懂事。 TY

0 个答案:

没有答案