Ruby-如何将评论列表添加到用户的仪表板?



我有三个表:books、comments和users。表格是相关的。用户可以登录,然后对书籍进行评论。用户有一个仪表板。如何让用户在仪表板上看到对其书籍的评论?以下是模型,book.rb:

class Book < ApplicationRecord
validates :title, presence: true
validates :author, presence: true
belongs_to :user
has_many :comments
end

comment.rb:

class Comment < ApplicationRecord
belongs_to :book
belongs_to :user
scope :approved, -> {where(status: true)}
end

user.rb:

class User < ApplicationRecord
before_create :set_username
has_many :books 
has_many :comments 

devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
attr_writer :login
def login
@login || self.username || self.email
end

# validates_length_of :username,
#                     :within => 5..50,
#                     :too_short => " is too short, must be at least 5 characters.",
#                     :presence => true
private
def set_username
self.username = self.email.split("@").first
end
def self.find_first_by_auth_conditions(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
else
if conditions[:username].nil?
where(conditions).first
else
where(username: conditions[:username]).first
end
end
end
end

仪表板控制器:

class DashboardController < ApplicationController
def index
@books = current_user.books
end
end

既然你已经有了这本书,你也可以加入注释来减少n+1。因此,在您的DashboardController中,您可以使用@books = current_user.books.includes(:comments)修改您的语句。这将收集该用户书籍的所有评论。然后在视图中,您可以像这样迭代它们。在那里你可以随心所欲地显示它们,即与孩子们一起查看评论

<% @books.each do |book| %>
<%= book.title %>
<%= book.author %>
<p>Comments:</p>
<% book.comments.each do |comment| %>
<%= comment.text %>
<% end %>
<% end %>

我有一些建议给你。你可以这样写

class DashboardController < ApplicationController
def index
@books = current_user.books.includes(:comments)
end
end

它将获得您需要的所有注释,尤其是您还可以避免n+1查询。

或者你也可以写

class DashboardController < ApplicationController
def index
@books = current_user.books
@comments = current_user.comments.where('id = ?', @books.pluck(:id))
end
end

最新更新