0
0

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 1 year has passed since last update.

【sampleメソッド】collection_selectで取得するデータをサンプルデータに取り入れる

Posted at

はじめに

seedsにform.collection_selectで取得するデータを保存する方法を紹介します。

サンプルコードについて

ユーザーの新規登録には、name、email、password、prefecture_idが必要です。
prefecture_idは、Prefectureテーブル(47都道府県)からcollection_selectでデータを取得します。

newアクション

/app/controllers/users_controller.rb
def new
  @prefectures = Prefecture.all
  @user = User.new
end

Prefectureテーブルから全レコード取得

作成フォーム

/app/views/users/new.html.haml
%h1 Sign up
.row
  = form_with(model: @user, local: true) do |f|
    = render 'shared/error_messages', object: f.object
    %div
      = f.label :name
      = f.text_field :name
    %div
      = f.label :email
      = f.email_field :email
    %div
      = f.label :password
      = f.password_field :password
    %div
      = f.label :password_confirmation
      = f.password_field :password_confirmation
    %div
      = f.label :prefecture_id
      = f.collection_select(:prefecture_id, @prefectures, :id, :name )
    %div
      = f.submit "Create my account"

sampleメソッド

/db/seeds.rb
50.times do |n|
name  =     Faker::Name.name
email =    "example-#{n+1}@testuser.org"
password = "password"
prefecture = Prefecture.all.sample.id
User.create!(name:                  name,
             email:                 email,
             prefecture_id:         prefecture,
             password:              password,
             password_confirmation: password)
end

sampleメソッドでPrefecture.allからランダムに1レコード取得、そのレコードからid属性を取得します。

あとがき

配列からランダムに1つオブジェクトを取得する方法は他にもあります。例えばshuffleメソッド

@prefecture = Prefecture.all.shuffle.first

sampleメソッドの方がコード量も少なく、シンプルで分かりやすいと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?