LoginSignup
4
2

More than 3 years have passed since last update.

【Rails 備忘録】「has_many先が存在しない場合に除外してインスタンス変数に格納」する書き方。

Last updated at Posted at 2019-06-27

はじめに

忘れてしまいがちなので備忘録。

条件

Projectモデルに、has_manyでParticipationモデルが関連付けされている。

createされたprojectにuserが参加アクションをすると、participationが該当のprojectにぶら下がる形でcreateされる。

なので、Projectのインスタンスであるprojectがparticipationを持っていない( @project.participations => [] )ということがありえる。

project.rb
class Project < ApplicationRecord
  has_many :participations



viewでparticipationを持っているprojectだけを表示したい。

やり方として一番簡単そうなのは、例えばcontrollerで
@projects = Project.where(user: current_user)
みたいな感じにして、viewテンプレートで

show.html.erb
<%= @projects.each do |project| %>
  <% if project.participations.present? %>
    <% project.name %>
  <% end %>
<% end %>

↑と書いてしまえばよいが、if文で毎回チェックさせるのもイマイチなので、
 controllerで@projectを格納するタイミングでparticipationがないものを除外させたい。

participationを持っているprojectだけを格納したい

答えを先に書くと、includeswhereを駆使して、

.includes(:participations).where(participations: Participation.all)
みたいな書き方をすればよい。

↓例:

participations_controller.rb
class ParticipationsController < ApplicationController

  def show
    @participation = Participation.find(params[:id])
    @participations = Participation.search_by_client(current_client)
    @projects = Project.where(client: current_client).where.not(status: "finished").
                  includes(:participations).where(participations: @participations)
  end

show.html.erb
<%= @projects.each do |project| %>
  <% project.name %>
<% end %>
4
2
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
4
2