How does Rails handle has_many when using requests?

If I have a User model that has many posts, how many queries will Rails execute against the database in the following scenario?

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

Is the fact that I use includesin the original query any kind of magic when I iterate over the returned messages in a method has_posted?to prevent multiple searches on the message table for each user?

+4
source share
1 answer

, , , has_posted? ?

.

.includes(), , N + 1. N . .includes() post . , , ... has_posted? posts.any?.

UPDATE

, ! , ruby. :

class User
  def has_posted?
    posts.is_posted.any?
  end
end

class Post
  scope :is_posted, -> { where(posted: true) }
end

, , posted true. .any? COUNT ! ( , .)

+2

Source: https://habr.com/ru/post/1542260/


All Articles