行为可读的Rails插件问题

时间:2020-03-05 18:42:09  来源:igfitidea点击:

我正在为当前正在构建的消息传递系统使用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.

有很多职位,这将是非常糟糕的表现。

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

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

这应该进入Post模型中,以遵循在视图或者控制器中不包含查找器的最佳实践

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) %>