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

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

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

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

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

Q&A

2回答

1483閲覧

メインのモデルと関連したモデルの値をplaceholderで表示したい

takuma1229

総合スコア11

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

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

0グッド

0クリップ

投稿2021/06/11 12:59

編集2021/06/17 02:38

前提・実現したいこと

railsでwebサービスを作っています。

Usersモデルと相関のあるDetailsモデル(このモデルはuser_idカラムでUsersモデルと繋げています)に存在する値を、フォームのplaceholderで表示する機能を実装しています。
この二つのモデルの関係は一対一です。
editページにおける実装で、コントローラのeditメソッドが該当しています。

ソースコードは下述いたします。

@user.nameはplaceholderで期待通り表示されるのですが、@detail.mother_tongueが表示されません。

どこに問題があるか教えていただきたいです。

程度の低い質問でしたら申し訳ございません。
また、質問に必要な情報等に不足があれば、お手数ですがご指摘いただければ、追記いたします。

よろしくお願いいたします。

該当のソースコード

ruby

1[users_controller.rb] 2class UsersController < ApplicationController 3 4 def show 5 @user = User.find(params[:id]) 6 end 7 8 def new 9 @user = User.new 10 end 11 12 def signup_jp 13 @user = User.new 14 end 15 16 def create 17 @user = User.new(user_params) 18 if @user.save 19 log_in @user 20 flash[:success] = "Welcome to INTE! Your account has been creaeted." 21 redirect_to details_path 22 else 23 flash[:danger] = "Invalid user information. Confirm that you filled all boxes except optional." 24 render 'new' 25 end 26 end 27 28 def details 29 end 30 31 def details_create 32 @detail = Detail.new(detail_params) 33 if @detail.save 34 redirect_to "/users/#{current_user.id}" 35 else 36 render 'details' 37 end 38 end 39 40//該当箇所はここです 41 def edit 42 @user = User.find(params[:id]) 43 @detail = Detail.find_by(user_id: @user.id) 44 end 45 46 47 private 48 49 def user_params 50 params.require(:user).permit(:name, :email, :image, :password, :password_confirmation) 51 end 52 53 def detail_params 54 params.permit(:authenticity_token, :user_id, :mother_tongue, :japanese_level, :english_level, 55 :gender, :region, :purpose, :self_introduction, :sns_1, :sns_2, :sns_3) 56 end 57 58end 59

html

1[edit.html.erb] 2<% provide(:title, 'edit') %> 3 4<div class="edit-wrapper"> 5 <h1 class="edit">Edit</h1> 6 7 <div class="row signup-forms"> 8 <div class="col-md-6 col-md-offset-3"> 9 <%= form_with(model: @user, local: true) do |f| %> 10 <%= render 'shared/error_messages'%> 11 12 <%= f.label :name, "Nickname" %> 13 <%= f.text_field :name, class: 'form-control', placeholder: "#{@user.name}" %> 14 15 <%= f.label :image %> 16 <%= f.file_field :image, class: "form-control image-form" %> 17 18 <%= f.label :mother_tongue, "Mother Tongue | 母語" %> 19 <%= f.select :mother_tongue, [["English", "English"], ["Japanese", "Japanese"], 20 ["Other","other"]], include_blank: "Please select.", class:"form-control",placeholder: #{@detail.mother_tongue}" %> //該当箇所はここです 21 22 23 <%= f.text_field :user_id, type: "hidden", value: "#{current_user.id}" %> 24 25 26 <%= f.submit "Create Your Account", class: "btn btn-primary create" %> 27 <% end %> 28 </div> 29 </div> 30</div>

ruby

1[detail.rb] 2class Detail < ApplicationRecord 3 belongs_to :user 4 validates :mother_tongue, presence: true 5 validates :japanese_level, presence: true 6 validates :english_level, presence: true 7 validates :region, presence: true 8 validates :purpose, presence: true 9 validates :self_introduction, presence: true, length: {maximum:300} 10end 11

ruby

1[user.rb] 2class User < ApplicationRecord 3 attr_accessor :remember_token 4 before_save {self.email = email.downcase} 5 validates :name, presence: true, length: {maximum: 20} 6 VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(.[a-z\d\-]+)*.[a-z]+\z/i 7 validates :email, presence: true, length: {maximum:255}, 8 format: {with: VALID_EMAIL_REGEX}, 9 uniqueness: true 10 has_secure_password 11 validates :password, presence: true, length: {minimum: 6} 12 mount_uploader :image, ImageUploader 13 14 def display_image 15 image.variant(resize_to_limit: [500, 500]) 16 end 17 18 def User.digest(string) 19 cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : 20 BCrypt::Engine.cost 21 BCrypt::Password.create(string, cost: cost) 22 end 23 24 def User.new_token 25 SecureRandom.urlsafe_base64 26 end 27 28 def remember 29 self.remember_token = User.new_token 30 update_attribute(:remember_digest, User.digest(remember_token)) 31 end 32 33 def authenticated?(remember_token) 34 return false if remember_digest.nil? 35 BCrypt::Password.new(remember_digest).is_password?(remember_token) 36 end 37 38 def forget 39 update_attribute(:remember_digest, nil) 40 end 41 42end 43

html

1[new.html.erb]//ユーザー新規登録のビューです 2<% provide(:title, 'Sign up') %> 3 4<div class="signup-wrapper"> 5 <h1 class="Signup">Sign up</h1> 6 7 <div class="row signup-forms"> 8 <div class="col-md-6 col-md-offset-3"> 9 <%= form_with(model: @user, local: true) do |f| %> 10 <%= render 'shared/error_messages'%> 11 12 <%= f.label :name, "Nickname" %> 13 <%= f.text_field :name, class: 'form-control' %> 14 15 <%= f.label :email %> 16 <%= f.email_field :email, class: "form-control" %> 17 18 <%= f.label :password %> 19 <%= f.password_field :password, class: "form-control" %> 20 21 <%= f.label :password_confirmation, "Confirmation" %> 22 <%= f.password_field :password_confirmation, class: "form-control" %> 23 24 <%= f.label :image %> 25 <%= f.file_field :image, class: "form-control image-form" %> 26 27 28 <%= f.submit "Create Your Account", class: "btn btn-primary create" %> 29 <% end %> 30 </div> 31 </div> 32</div>

html

1[details.html.erb]//detail(ユーザー詳細情報)登録画面のビューです 2<% provide(:title, "user detail") %> 3 4<div class="user-detail-wrapper"> 5 <div class="introduction"> 6 <h3>①Authorize your account via sent Email. | 送信されたメールからアカウント認証を行なってください。</h3> 7 <h3>②Let's register your user informations! | ユーザー情報を登録しましょう!<br>You can change it later. | この情報は後から修正可能です。</h3> 8 </div> 9 10 <div class="row user-detail-forms"> 11 <div class="col-md-6 col-md-offset-3"> 12 <%= form_with(model: @detail, local: true) do |f| %> 13 14 15 <%= f.label :mother_tongue, "Mother Tongue | 母語" %> 16 <%= f.select :mother_tongue, [["English", "English"], ["Japanese", "Japanese"], 17 ["Other","other"]], include_blank: "Please select.", class:"form-control" %> 18 19 <%= f.label :japanese_level, "Japanese Level | 日本語のレベル" %> 20 <%= f.select :japanese_level, [["Beginner | 初心者", "Beginner | 初心者"], ["Capable of quite basic communication | 簡単な会話ならできる", "Capable of quite basic communication | 簡単な会話ならできる"], 21 ["Capable of daily conversation | 日常会話ができる","Capable of daily conversation | 日常会話ができる"], ["Capable of advanced conversation | 難しい内容の会話ができる","Capable of advanced conversation | 難しい内容の会話ができる"], ["Almost native level | ネイティブとほとんど同レベル","Almost native level | ネイティブとほとんど同レベル"], 22 ["Native | ネイティブ","Native | ネイティブ"]], include_blank: "Please select.", class:"form-control" %> 23 24 <%= f.label :english_level, "English Level | 英語のレベル" %> 25 <%= f.select :english_level, [["Beginner | 初心者", "Beginner | 初心者"], ["Capable of quite basic communication | 簡単な会話ならできる", "Capable of quite basic communication | 簡単な会話ならできる"], 26 ["Capable of daily conversation | 日常会話ができる","Capable of daily conversation | 日常会話ができる"], ["Capable of advanced conversation | 難しい内容の会話ができる","Capable of advanced conversation | 難しい内容の会話ができる"], ["Almost native level | ネイティブとほとんど同レベル","Almost native level | ネイティブとほとんど同レベル"], 27 ["Native | ネイティブ","Native | ネイティブ"]], include_blank: "Please select.", class:"form-control" %> 28 29 <%= f.label :gender, "Gender(optional) | ジェンダー(任意)" %> 30 <%= f.select :gender, [["he/him | 男性", "he/him | 男性"], ["she/her | 女性", "she/her | 女性"], 31 ["they/them | その他","they/them | その他"], ["I don't want to tell | 言いたくない","I don't want to tell | 言いたくない"]], include_blank: "Please select.", class:"form-control" %> 32 33 <%= f.label :region, "Region | 地域" %> 34 <%= f.select :region, [["Asia | アジア", "Asia | アジア"], ["Europe |ヨーロッパ", "Europe | ヨーロッパ"], 35 ["Africa | アフリカ","Africa | アフリカ"], ["North/Central America | 北/中央アメリカ","North/Central America | 北/中央アメリカ"], ["South America | 南アメリカ","South America | 南アメリカ"], 36 ["Oceania | オセアニア","Oceania | オセアニア"], ["Other | その他","Other | その他"]], include_blank: "Please select.", class:"form-control" %> 37 38 39 40 <%= f.text_field :user_id, type: "hidden", value: "#{current_user.id}" %> 41 42 43 <%= f.submit "Send | 送信", class: "btn btn-primary create" %> 44 <% end %> 45 </div> 46 </div> 47</div>

ruby

1[sessions_helper.rb] 2module SessionsHelper 3 4 def log_in(user) 5 session[:user_id] = user.id 6 end 7 8 def remember(user) 9 user.remember 10 cookies.permanent.signed[:user_id] = user.id 11 cookies.permanent[:remember_token] = user.remember_token 12 end 13 14 def current_user 15 if(user_id = session[:user_id]) 16 @current_user ||= User.find_by(id: user_id) 17 elsif(user_id = cookies.signed[:user_id]) 18 user = User.find_by(id: user_id) 19 if user && user.authenticated?(cookies[:remember_token]) 20 log_in user 21 @current_user = user 22 end 23 end 24 end 25 26 def logged_in? 27 !current_user.nil? 28 end 29 30 def log_out 31 session.delete(:user_id) 32 @current_user = nil 33 end 34 35 def forget(user) 36 user.forget 37 cookies.delete(:user_id) 38 cookies.delete(:remember_token) 39 end 40 41 def log_out 42 forget(current_user) 43 session.delete(:user_id) 44 @current_user = nil 45 end 46end

補足情報(FW/ツールのバージョンなど)

Rails 6.0.3
Ruby 2.6.3
AWS Cloud9を使用

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

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

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

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

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

guest

回答2

0

エラーログは表示されているでしょうか?
表示されていれば掲載していただきたいです。

user_idが登録できているか怪しい気がするので、
登録画面のコードも載せていただきたいです。

投稿2021/06/12 04:16

genki0126

総合スコア33

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

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

takuma1229

2021/06/15 06:43

回答ありがとうございます。 返信が遅くなってしまい大変申し訳ございません。 エラーログ等は特に表示されておりません。 登録画面のコードとは、ユーザー登録画面のビューのコードということでしょうか?
genki0126

2021/06/15 23:14

>登録画面のコードとは、ユーザー登録画面のビューのコードということでしょうか? はい。そうです。
takuma1229

2021/06/17 00:40

追加いたしました。 よろしくお願いいたします。
genki0126

2021/06/17 02:33

current_userの定義はどこでされていますか? 定義部分を見てみたいです。
takuma1229

2021/06/17 02:40

current_userの定義が書いてあるsessions_helper.rbをいま追加しました。 よろしくお願いいたします。
genki0126

2021/06/17 02:47

def current_user内で使われている「user_id」はどこで定義されているものでしょうか? それとcurrent_user内のif分の条件式が比較演算子ではなく代入になっています。
takuma1229

2021/06/17 03:19

user_idはcurrent_user内で新しく定義している変数です! if内の条件式も、代入のつもりで書いております
genki0126

2021/06/17 03:44

失礼しました。自分の知識不足でした。 [details.html.erb]を開くときのアクションはdetailsですか? [details.html.erb]のform_withに渡している@detailはどこで定義されているでしょうか?
guest

0

placeholder: #{@detail.mother_tongue}"
始まりの ダブルコーテーション が無いからでは?

placeholder: @detail.mother_tongue で行けると思いますが。

投稿2021/06/11 13:17

winterboum

総合スコア23347

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

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

takuma1229

2021/06/11 13:53

回答ありがとうございます。 ダブルコーテーションの抜けは転記時のミスで、元のコードには問題なくついておりましたが、うまく動きません。 大変失礼いたしました。 少し考えてみて気づいたのですが、f.selectにはplaceholderを使えないようなので `<%= f.select :mother_tongue, [["English", "English"], ["Japanese", "Japanese"], ["Other","other"]], include_blank: "Please select.", class:"form-control",value: "#{@detail.mother_tongue} " %>` このようにしてみたのですが、ダメでした...
takuma1229

2021/06/11 13:58

placeholderではなくvalueを設定した、という旨の変更です。
winterboum

2021/06/11 20:58

ああ、、そういえば、、、 include_blank: @detail.mother_tongue ではどうです?
takuma1229

2021/06/15 06:42

回答が遅くなり申し訳ございません。 include_blank: @detail.mother_tongue、試してみました。 セレクトボックスを開いた際の最初の選択肢としては表示されてくれたのですが、セレクトボックスを開く前の表示(placeholder的な表示)としては機能してくれませんでした...
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問