LoginSignup
tawa19
@tawa19

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

[Ruby on Rails]異性のみを表示させる設定が上手くいかない

解決したいこと

Ruby on Railsを使い、マッチングアプリ風のものを作っています。
indexページで異性のみを表示させる設定を行いたいのですが上手くいきません。

現状のコード

migrate/2023xxxxxx_create_users.rb
class CreateUsers < ActiveRecord::Migration[7.1]
  def change
    create_table :users do |t|
      t.string :name
      t.string :email
      t.string :gender, null: false, default: '未設定'
      t.date :birthday
      t.text :profile, limit: 800
      t.string :avatar
      t.string :live, null: false, default: '未設定'

      t.timestamps
    end
  end
end

ユーザー作成ページ

views/users/new.html.erb
<% provide(:title, 'Sign up') %>
<h1>新規登録</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_with(model: @user) do |f| %>
      <%= render 'shared/error_messages' %>


~~~~~~


      <%= f.label :gender, '性別' %>
      <%= f.select :gender, {'男性': '男性', '女性': '女性'}, { include_blank: '選択してください'}, { class: 'form-control' , required: true } %>


~~~~~~


      <%= f.submit "登録", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>

seedでユーザー追加

db/seed.rb
#日本名
Faker::Config.locale = :ja

# 男性のユーザーをまとめて生成する
50.times do |n|
  name = "male#{n+1}"
  email = "male-#{n+1}@samplemtapp.org"
  password = "password"
  User.create!(name:                  name,
               email:                 email,
               password:              password,
               password_confirmation: password,
               gender:                '男性',
               birthday: Faker::Date.birthday(min_age: 18, max_age: 50),
               profile:  Faker::Lorem.sentence,
               live:     Faker::Address.state)
end

# 女性のユーザーをまとめて生成する
50.times do |n|
  name = "female#{n+1}"
  email = "female-#{n+1}@samplemtapp.org"
  password = "password"
  User.create!(name:                  name,
               email:                 email,
               password:              password,
               password_confirmation: password,
               gender:                '女性',
               birthday: Faker::Date.birthday(min_age: 18, max_age: 50),
               profile:  Faker::Lorem.sentence,
               live:     Faker::Address.state)
end

controllerでindexページに表示するユーザーを制限したい

user_controller.rb
class UsersController < ApplicationController
  before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
  before_action :correct_user,   only: [:edit, :update]
  before_action :admin_user,     only: :destroy

  def index
    # 性別の異なるユーザーを取得(自分以外)。ここで制限をかける。
    @users = User.where.not(id: current_user.id, gender: current_user.gender).paginate(page: params[:page]).order("created_at DESC")
  end


~~~~~~
  (以下省略)

end

indexページでは特に何も制限かけてません。

views/users/index.html.erb
<%= will_paginate %>

<ul class="users">
  <% @users.each do |user| %>
    <%= render user %>
  <% end %>
</ul>

<%= will_paginate %>
views/users/_user.html.erb
<li>
  <% if user.avatar.present? %>
    <%= image_tag user.avatar.url, size: 50 %> <!-- ユーザープロフィール画像 -->
  <% else %>
    <%= image_tag "8d27ad3552fd86901f4976429ad22ce2.png", size: 50 %> <!-- プロフィール画像未設定時のデフォルト画像 -->
  <% end %>
  <%= link_to user.name, user %>

  <%= user.age %>歳 <%= user.live %>
</li>

現在の画面

indexページの画面を見ると男性、女性、両方とも表示されてしまっている。
(maleが男性設定、femaleが女性設定)
スクリーンショット 2023-12-16 22.24.58.png


↑はlocalhostの画面です。少しでも手掛かりになること教えていただけたら嬉しいです。

0

2Answer

where.not(id: current_user.id, gender: current_user.gender) は「『ユーザー ID が current_user.id かつ性別が current_user.gender』ではないユーザー」に絞り込むため、 current_user 以外すべてのユーザーが選ばれてしまっています。

「ユーザー ID が current_user.id ではなく、性別が current_user.gender ではないユーザー」に絞り込みたいので、 where.not(id: current_user.id).where.not(gender: current_user.gender) としてください。

2

Comments

  1. @tawa19

    Questioner

    説明されるとその通りですね。気づきませんでした。
    ありがとうございます。

シンプルに「性別がcurrent_user.genderではない」でもよさそうに見えます。
例えばユーザーのIDが123で性別が男性の場合、「男性以外」にはそもそもID123は含まれませんので。

image.png

図左:『ユーザー ID が current_user.id かつ性別が current_user.gender』ではないユーザー
図右:ユーザー ID が current_user.id ではなく、性別が current_user.gender ではないユーザー

2

Comments

  1. @tawa19

    Questioner

    同性の範囲に自分が含まれているのでそうですね。
    わかりやすいべん図をありがとうございます。

Your answer might help someone💌