我正在使用Intridea的Acts as Readable 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>]因此,如果我想列出邮箱中未读邮件的数量(例如,收件箱(39) ),我应该能够这样做:
<%= Post.find_unread_by(current-user).count %>但无济于事。在一切就绪之后,我似乎总是被简单的视图问题卡住了。有什么想法吗?
发布于 2008-08-22 18:33:34
下面的方法将会起作用
<%= Post.find_unread_by(current_user).size %>或
<%= Post.find_unread_by(current_user).length %>但是,如果您检查您的development.log,您应该看到它通过以下方式获得未读计数
这将是非常糟糕的性能智慧与大量的帖子。
更好的方法是检索当前用户读取的帖子,然后使用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) %>https://stackoverflow.com/questions/22980
复制相似问题