【发布时间】:2014-05-28 01:12:21
【问题描述】:
如果我有一个包含许多帖子的用户模型,Rails 将在以下场景中对数据库执行多少次查询?
class User
has_many :posts
# this is the main method in question...
def has_posted?
posts.any? {|p| p.posted? }
end
end
# has an attr "posted" which is a boolean
class Post
belongs_to :user
end
# some controller
users = User.includes(:posts).all
# in the view
<% users.each do |user| %>
<%= 'posted!' if user.has_posted? %>
<% end %>
当我在has_posted? 方法中循环返回的帖子以防止对每个用户的帖子表进行多次查找时,我在初始查询中使用includes 的事实是否有任何魔力?
【问题讨论】:
标签: ruby-on-rails ruby database performance