ruby-on-rails - 当前用户只能看到对其帖子的评论

标签 ruby-on-rails ruby devise

我有什么:

scaffold Post title body user_id
scaffold Comment body tag post:references
post has_many :comments

当前评论 Controller :

  def index
    @comments = Comment.where(tag: [1, 3])
  end

我想让当前的设计用户只看到他的所有帖子的评论列表。如何做呢?与 current_user 有关吗?

最佳答案

你可以直接在 User 模型上设置一个 has_many :through 关系假设你已经定义了一个 has_many :posts 关系并且适当的PostComment 的关系。例如,

class User < ActiveRecord::Base
  has_many :posts
  has_many :comments, through: :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

现在,由于 devise 为您提供 current_user,因此获取用户的评论很简单

def index
  @comments = current_user.comments
end

def show
  @comment = current_user.comments.find(params[:id])
end

希望这对您有所帮助。干杯。

关于ruby-on-rails - 当前用户只能看到对其帖子的评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35672942/

相关文章:

ruby-on-rails - 设备可锁定第 n 次尝试时的自定义消息

ruby-on-rails - 使用 Capybara 和 Javascript 测试重定向

ruby-on-rails - Rails hash to array to hash 如何?

ruby-on-rails - 充当Voable获取Upvotes错误

Ruby:访问对象时 alias_method 的意外行为

java - 如果我没有与之共享,JRuby 中的 Ruby 脚本可以使用我的 Java 类吗?

ruby-on-rails - 在用户选择框中使用设计当前用户作为默认用户

mysql - 设备迁移错误

ruby-on-rails - 将相同的列名添加到不同的表 - Rails 迁移

ios - 在 iOS 中加载多个图像时,使用 send_data 加载的图像半损坏