質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.46%
Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

1回答

3330閲覧

Railsで個体識別番号を自動採番したい

ahiru3

総合スコア12

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2020/08/11 20:51

編集2020/08/18 21:06

前回の質問の回答を実装したいので助けて欲しいです。
目的はuser_idごとに”年、月”-”番号”というような個体番号を新規登録ごとにふりたいです。
現在の状況記載します。

controllers

1class FamiliesController < ApplicationController 2 before_action :authenticate_user!, except: [:index] 3 def index 4 @families =Family.all.order(created_at: "DESC") 5 end 6 7 def show 8 @family = Family.find(params[:id]) 9 end 10 11 def new 12 @family = Family.new 13 end 14 15 def create 16 @family = Family.new(family_params) 17 @family.user_id = current_user.id 18 if @family.save 19 redirect_to family_path(@family), notice: "登録完了しました。" 20 else 21 render :new 22 end 23 end 24 25 def edit 26 @family = Family.find(params[:id]) 27 if @family.user != current_user 28 redirect_to families_path, alert: "不正なアクセスです。" 29 end 30 end 31 32 def update 33 @family = Family.find(params[:id]) 34 if @family.update(family_params) 35 redirect_to family_path(@family), notice: "更新に成功しました。" 36 else 37 render :edit 38 end 39 end 40 41 def destroy 42 family = Family.find(params[:id]) 43 family.destroy 44 redirect_to families_path 45 end 46 private 47 def family_params 48 params.require(:family).permit(:category, :molph, :individualnumber, :image, :fathermolph, :mothermolph, :hatchdate, :sex, :weight, :feature) 49 end 50end 51

migrate

1class CreateFamilies < ActiveRecord::Migration[5.2] 2 def change 3 create_table :families do |t| 4 t.integer :user_id 5 t.string :category 6 t.string :molph 7 t.string :individualnumber 8 t.string :image_id 9 t.string :fathermolph 10 t.string :mothermolph 11 t.date :hatchdate 12 t.string :sex 13 t.integer :weight 14 t.text :feature 15 16 t.timestamps 17 end 18 end 19end

routes

1Rails.application.routes.draw do 2 devise_for :users 3 root to: "home#index" 4 resources :users 5 resources :families 6end

newhtml

1<section class="hero is-success"> 2 <div class="hero-body"> 3 <div class="container"> 4 <h1 class="title"> 5 new family 6 </h1> 7 </div> 8 </div> 9</section> 10 11 <% if @family.errors.any? %> 12 <div class="notification is-danger"> 13 <h2><%= pluralize(@family.errors.count, "error") %> prohibited this object from being saved: not successfully</h2> 14 <ul> 15 <% @family.errors.full_messages.each do |message| %> 16 <li><%= message %></li> 17 <% end %> 18 </ul> 19 </div> 20 <% end %> 21 22<section class="section"> 23 <div class="container"> 24 <div class="columns is-centered"> 25 <div class="column is-6"> 26 <%= form_for @family do |f| %> 27 <div class="field"> 28 <%= f.label :category, "カテゴリー", class: "label" %> 29 <%= f.text_field :category, class: "input" %> 30 </div> 31 <div class="field"> 32 <%= f.label :molph, "モルフ", class: "label" %> 33 <%= f.text_field :molph, class: "input" %> 34 </div> 35 <div class="field"> 36 <%= f.label :individualnumber, "個体番号", class: "label" %> 37 <%= f.month_field :individualnumber, class: "input" %> 38 </div> 39 <div class="field"> 40 <%= f.label :image, "写真", class: "label" %> 41 <%= f.attachment_field :image, class: "input" %> 42 </div> 43 <div class="field"> 44 <%= f.label :fathermolph, "父親モルフ", class: "label" %> 45 <%= f.text_field :fathermolph, class: "input" %> 46 </div> 47 <div class="field"> 48 <%= f.label :mothermolph, "母親モルフ", class: "label" %> 49 <%= f.text_field :mothermolph, class: "input" %> 50 </div> 51 <div class="field"> 52 <%= f.label :hatchdate, "ハッチデータ", class: "label" %> 53 <%= f.date_field :hatchdate, class: "input" %> 54 </div> 55 <div class="field"> 56 <%= f.label :sex, "雌雄", class: "label" %> 57 <%= f.select :sex, [["♂", "♂"], ["♀", "♀"],["不明","不明"]], include_blank: "選択して下さい" %> 58 </div> 59 <div class="field"> 60 <%= f.label :weight, "体重", class: "label" %> 61 <%= f.number_field :weight, class: "input" %> 62 </div> 63 <div class="field"> 64 <%= f.label :feature, "特徴", class: "label" %> 65 <%= f.text_area :feature, class: "textarea" %> 66 </div> 67 68 <%= f.submit "登録", class: "button is-success" %> 69 70 <% end %> 71 </div> 72 </div> 73 </div> 74</section> 75

下記のmew.htmlの個体番号を”年、月”-”番号”で自動採番もしくは、
年、月は選択で番号は自動採番できますでしょうか。

  <div class="field"> <%= f.label :individualnumber, "個体番号", class: "label" %> <%= f.month_field :individualnumber, class: "input" %> </div>

よろしくお願いします。

追記

familiescontroller

1def create 2 @family = Family.new(family_params) 3 @family.get_serial 4 @family.user_id = current_user.id 5 if @family.save 6 redirect_to family_path(@family), notice: "登録完了しました。" 7 else 8 render :new 9 end 10 end 11 12 def get_serial 13 month = Date.parse(individualnumber+"/1").strftime("%Y年%m月-") 14 number = where("individualnumber like ?"."#{month}%"). 15 order(individualnumber: :desc). 16 first.individualnumber[/月-(\d+)/,1].succ 17 self.individualnumber = month + number 18 end

上記のように記載しました。
すると下記のエラーが出ています。

app/controllers/families_controller.rb:28: syntax error, unexpected tSTRING_BEG
app/controllers/families_controller.rb:28: syntax error, unexpected ')', expecting end

28

1number = where("individualnumber like ?"."#{month}%").

です。

追記2

familymodel

1class Family < ApplicationRecord 2 belongs_to :user 3 attachment :image 4 5 with_options presence: true do 6 validates :category 7 validates :molph 8 validates :image 9 validates :fathermolph 10 validates :mothermolph 11 validates :hatchdate 12 validates :sex 13 validates :weight 14 validates :feature 15 end 16 17 def get_serial 18 month = Date.parse(individualnumber+"/1").strftime("%y年%m月-") 19 number = Family.where("individualnumber like ?","#{month}%"). 20 order(individualnumber: :desc). 21 first.individualnumber[/月-(\d+)/,1].succ 22 self.individualnumber = month + number 23 end 24end

familycontroller

1 def create 2 @family = Family.new(family_params) 3 @family = get_serial 4 @family.user_id = current_user.id 5 if @family.save 6 redirect_to family_path(@family), notice: "登録完了しました。" 7 else 8 render :new 9 end 10 end

上記ように変更しました。
エラー内容

となります。
methodが定義されていないのでしょうか。。。

追記③

何を変更していいのやら全くわからないです。
何が違ってますでしょうか。

familyrb

1class Family < ApplicationRecord 2 belongs_to :user 3 attachment :image 4 5 with_options presence: true do 6 validates :category 7 validates :molph 8 validates :image 9 validates :fathermolph 10 validates :mothermolph 11 validates :hatchdate 12 validates :sex 13 validates :weight 14 validates :feature 15 end 16 17 def get_serial 18 month = Date.parse(individualnumber+"/1").strftime("%y年%m月-") 19 number = Family.where("individualnumber like ?","#{month}%"). 20 order(individualnumber: :desc). 21 first.individualnumber[/月-(\d+)/,1].succ 22 self.individualnumber = month + number 23 end 24end

追記④

modelfamily

1def get_serial 2 month = Date.parse(individualnumber+"/1").strftime("%y年%m月-") 3 number = Family.where("individualnumber like ?","#{month}%"). 4 latest = where("individualnumber like ?"."#{month}%"). 5 order(individualnumber: :desc).first 6 number = latest ? latest.individualnumber[/月-(\d+)/,1].succ : 1 7 self.individualnumber = month + number 8 end

これでいいのですか?

以下のエラーになりました。
イメージ説明

追記⑤

like ?"."#{month}%"がカンマの部分を直して上のエラーは無くなりました。
次はNo method errorで止まってしましました。

イメージ説明

model family.rb

class Family < ApplicationRecord belongs_to :user attachment :image with_options presence: true do validates :category validates :molph validates :image validates :fathermolph validates :mothermolph validates :hatchdate validates :sex validates :weight validates :feature end def get_serial month = Date.parse(individualnumber+"/1").strftime("%y年%m月-") number = Family.where("individualnumber like ?","#{month}%"). latest = where("individualnumber like ?","#{month}%"). order(individualnumber: :desc).first number = latest ? latest.individualnumber[/月-(\d+)/,1].succ : 1 self.individualnumber = month + number end end

families.controller

class FamiliesController < ApplicationController 省略 def create @family = Family.new(family_params) @family.get_serial @family.user_id = current_user.id if @family.save redirect_to family_path(@family), notice: "登録完了しました。" else render :new end end def edit @family = Family.find(params[:id]) if @family.user != current_user redirect_to families_path, alert: "不正なアクセスです。" end end def update @family = Family.find(params[:id]) if @family.update(family_params) redirect_to family_path(@family), notice: "更新に成功しました。" else render :edit end end

質問ばっかりすいません。

よろしくお願いします。

追記⑥
イメージ説明

qiitaやteratailsで探したのですがgemfileの更新などが出てきました。
やっていいものかわからなかったので確認のため質問します。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

individualnumber のDBにしまわれる値は "2020年8月-12" としたいが、登録時の入力は 2020/8 として、追い番は自動採番としたい

という意味と取って考えます。
個人で使うもののようですから入力のエラーチェックなどは省いちゃいます。

まず、"2020年8月-12" ではなく "2020年08月-12"にさせてください。
入力は 2020/08、2020-8 の様に入れる、ということにします。
@family = Family.new(family_params) のあと
@family.get_serial とでも名付けたmethodを呼びます
class Family の中で

def get_serial month = Date.parse(individualnumber+"/1").strftime("%Y年%m月-") number = where("individualnumber like ?"."#{month}%"). order(individualnumber: :desc). first.individualnumber[/月-(\d+)/,1].succ self.individualnumber = month + number end

first.individualnumber までで "2020年08月-12" が得られ、その後ろの[ ] で "12" が、そして succ で "13"が得られます。
Date.parseで +"/1" してるのはエラーを起こしにくくするおまじない。

投稿2020/08/11 23:03

winterboum

総合スコア23408

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

ahiru3

2020/08/12 22:06

ありがとうございます。 馬鹿で申し訳ないのですが、 def create @family = Family.new(family_params) @family.get_serial @family.user_id = current_user.id if @family.save redirect_to family_path(@family), notice: "登録完了しました。" else render :new end end def get_serial month = Date.parse(individualnumber+"/1").strftime("%Y年%m月-") number = where("individualnumber like ?"."#{month}%"). order(individualnumber: :desc). first.individualnumber[/月-(\d+)/,1].succ self.individualnumber = month + number end 上記で良いのでしょうか。 これだと、 app/controllers/families_controller.rb:28: syntax error, unexpected tSTRING_BEG app/controllers/families_controller.rb:28: syntax error, unexpected ')', expecting end とエラーになりました。 聞いてばかりですいません。
winterboum

2020/08/12 22:31

codeはコメンtに書くとベタになって読みにくいので質問欄に追記でおねがいします。 で、28行目ってどこでしょう
ahiru3

2020/08/12 22:43

質問に追記しました。 すいません。
winterboum

2020/08/12 23:05

like ?"."#{m のが カンマですピリオドになってます。 それと def get_serial は modelに書いてください。 ミス。 whereの前に Family. をつけてください
ahiru3

2020/08/14 08:16

調べたのですがどこの何が足りないのかが不明です。 追記で質問しております。 すいませんがお願いします。
winterboum

2020/08/14 09:04

@family = get_serial でなく @family.get_serial です
ahiru3

2020/08/14 22:00

ありがとうございます。 どんどんエラー出てきて流のですが、 controllerにmethodが定義されていないということでしょうか。
winterboum

2020/08/14 22:59

@family = get_serial だと controllerのget_serialメソッドを呼んでます。 それだとエラーになるので @family.get_serial にしていただいて、@familyのget_serialを実行します。
ahiru3

2020/08/15 22:35

一つ前のコメントで@family = get.serialの指摘いただいたので、 @family.get.serialに変更しているのですが、他にも変更箇所はありますでしょうか。 追記3に変更を追加しておきます。
winterboum

2020/08/15 22:57

ああ、そうかごめんなさい、その月の最初の子牛のときエラーになってしまてました latest = where("individualnumber like ?"."#{month}%"). order(individualnumber: :desc).first number = latest ? latest.individualnumber[/月-(\d+)/,1].succ : 1 にしてください Nilにはindividualnumberがないというエラーなので、firstした結果がnilということです。
ahiru3

2020/08/17 20:16

質問ばかりだとダメだと思って調べてチャレンジしたのですが、 結局ダメでした。 追記⑤の状態で止まってしまっています。 すいませんが助けて下さい。 よろしくお願いします。
winterboum

2020/08/17 22:54

ごめんなさい、そこは私のミスで2020/08/13 08:05にコメントでいれてますように、 where を Family.where にしてください。
ahiru3

2020/08/18 20:56

ありがとうございます。 self.individualnumber = month + numberでTypeErrorが発生してしまいました。 追記しますのでお願いします。
winterboum

2020/08/18 22:13

month + number.to_s ですね。 このくらいは自力で見つけてほしいな
ahiru3

2020/08/19 19:47

すいませんでした。ありがとうございます。 sqliteのdb見ると年と月しか入っていなかったので、 ちょっと原因調べてみます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.46%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問