現在、簡単なSNSアプリを作ろうと思っているのですが、モデルの取り扱いについてわからなかったため質問いたします。
ユーザー1人はUserモデルとMyintroモデルを持っております.
Userモデルはdevise認証のGemで作ったものです。
1人のユーザーは1つの自分の詳細モデルを持つ、というイメージで考えており、
Userモデル1つにつき、Myintroモデルを1つ持っているものになります。
ここで、ユーザーを一人作った後、自分の詳細モデルを作る際
Myintroコントローラーのnewアクションを行うのですが
その中で、Userが持っているMyintroが一つであればeditページへ飛ばす、としたいのです。
質問
ユーザーがMyintroを一つ以上持っているならという条件を
if current_user.Myintro.length >=1
というようなコードで書けたらいいのですが、何かいい方法はありませんでしょうか?
Ruby
1class MyintrosController < ApplicationController 2 before_action :authenticate_user! 3 def index 4 5 end 6 def show 7 end 8 def new 9 # 現在のユーザーの紹介を作る 10 @length = current_user.myintro.length 11 # 現在のユーザーが詳細モデルをすでに持っていれば編集ページに遷移する 12 redirect_to edit_myintro_path(@myintro) 13 end 14 15 @myintro = current_user.build_myintro 16 end 17 18 def create 19 @myintro = current_user.build_myintro(myintro_params) 20 if @myintro.save 21 redirect_to edit_myintro_path(@myintro),notice:"プロフィール詳細を作成・保存しました" 22 else 23 redirect_to new_myintro_path,notice:"プロフィール詳細を作成できませんでした" 24 end 25 end 26 def edit 27 end 28 29 private 30 def myintro_params 31 params.require(:myintro).permit(:sex, :love_target) 32 end 33end 34
Ruby
1class Myintro < ApplicationRecord 2 belongs_to :user 3 4 #必須項目 5 validates :sex, presence: true 6 7end
Ruby
1class User < ApplicationRecord 2 # Include default devise modules. Others available are: 3 # :confirmable, :lockable, :timeoutable and :omniauthable 4 devise :database_authenticatable, :registerable, 5 :recoverable, :rememberable, :trackable, :validatable 6 has_one :myintro,dependent: :destroy 7end 8
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/04/23 14:59
2018/04/25 11:27
2018/04/25 15:40
2018/04/26 01:38
2018/04/26 14:57