1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsでincludesをwhereで絞り込みをする

Posted at

has_manyの第2引数にscopeを渡すよい

class User < ApplicationRecord
  has_many :published_articles, -> { where(state: 'published') }, class_name: Article
end

User.includes(:published_articles).published_articles

リファクタリング前

class User < ApplicationRecord
  has_many :articles
end

class Article < ApplicationRecord
  belongs_to :user
end

class UsersController < ApplicationController
  def index
    @users = User.includes(:articles)
  end
end
- @users.each do |user|
  - articles = user.articles.select { |article| article.state == 'published' }
  - articles.each do |article|
    p = article.title

リファクタリング後

class User < ApplicationRecord
  has_many :articles
  has_many :published_articles, -> { published }, class_name: Article
end

class Article < ApplicationRecord
  belongs_to :user
  scope :published, -> { where(state: 'published') }
end

class UsersController < ApplicationController
  def index
    @users = User.includes(:published_articles)
  end
end
- @users.each do |user|
  - user.published_articles.each do |article|
    p = article.title
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?