我正在使用 Intridea 的 充当可读的角色 我目前正在构建的消息系统的 Rails 插件。我相应地定义了我的消息类:

class Post < ActiveRecord::Base
  acts-as-readable
end

一切似乎都按计划进行,但是当尝试让应用程序在我的消息视图中显示未读消息时,我遇到了问题。

他们的例子:(由于格式问题,我已将下划线更改为连字符)

bob = User.find_by_name("bob")

bob.readings                      # => []

Post.find_unread_by(bob)          # => [<Post 1>,<Post 2>,<Post 3>...]
Post.find_read_by(bob)            # => []

Post.find(1).read_by?(bob)        # => false
Post.find(1).read_by!(bob)        # => <Reading 1>
Post.find(1).read_by?(bob)        # => true
Post.find(1).users_who_read       # => [<User bob>]

Post.find_unread_by(bob)          # => [<Post 2>,<Post 3>...]
Post.find_read_by(bob)            # => [<Post 1>]

bob.readings                      # => [<Reading 1>]

因此,如果我想列出邮箱中未读邮件的数量(例如 Inbox (39) ),我应该能够执行以下操作:

<%= Post.find_unread_by(current-user).count %>

但无济于事。一切设置完毕后,我似乎总是陷入简单的视图问题。有任何想法吗?

有帮助吗?

解决方案

以下将起作用

<%= Post.find_unread_by(current_user).size %>

或者

<%= Post.find_unread_by(current_user).length %>

但是,如果您检查development.log,您应该会看到它的未读计数为

  1. 检索所有帖子
  2. 检索用户阅读的所有帖子
  3. 2. 全部删除。从 1.在红宝石中

对于大量帖子来说,这将是非常糟糕的性能。

更好的方法是检索当前用户阅读的帖子,然后使用 ActiveRecord::Calculations 来获取计数,而无需检索数据库中的所有帖子

Post.count(:conditions => [ "id NOT IN (?)", Post.find_read_by(current_user)])

这应该进入您的 Post 模型,以遵循视图或控制器中没有查找器的最佳实践

后.rb

def self.unread_post_count_for_user(user)
  count(:conditions => [ "id NOT IN (?)", Post.find_read_by(user)])
end

那么你的观点将是

<%= Post.unread_post_count_for_user(current-user) %>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top