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

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

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

Deviseとは、Ruby-on-Railsの認証機能を追加するプラグインです。

Ruby

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

Ruby on Rails 4

Ruby on Rails4はRubyによって書かれたオープンソースのウェブフレームワークです。 Ruby on Railsは「設定より規約」の原則に従っており、効率的に作業を行うために再開発を行う必要をなくしてくれます。

Q&A

1回答

3017閲覧

NoMethodError (undefined method `name' for nil:NilClass)

HirokiShirai

総合スコア11

Devise

Deviseとは、Ruby-on-Railsの認証機能を追加するプラグインです。

Ruby

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

Ruby on Rails 4

Ruby on Rails4はRubyによって書かれたオープンソースのウェブフレームワークです。 Ruby on Railsは「設定より規約」の原則に従っており、効率的に作業を行うために再開発を行う必要をなくしてくれます。

0グッド

0クリップ

投稿2014/11/16 22:26

こんにちは。

以下の様なDeviseのジェネレータを用いて作成したモデルがあり、「:html => { :multipart => true }」オプションを追加したフォームからfile_field(icon)に画像ファイルを指定してcreateメソッドにsubmitしたところ、タイトルの「NoMethodError (undefined method `name' for nil:NilClass)」が発生しました。ただし、file_field(icon)に何も指定しないとicon以外は正しく保存されます。

db/schema.rb

lang

1ActiveRecord::Schema.define(version: 20141112025346) do 2 create_table "users", force: true do |t| 3 t.string "name", default: "", null: false 4 t.binary "icon", limit: 2147483647 5 t.string "email", default: "", null: false 6 t.string "encrypted_password", default: "", null: false 7 t.string "reset_password_token" 8 t.datetime "reset_password_sent_at" 9 t.datetime "remember_created_at" 10 t.integer "sign_in_count", default: 0, null: false 11 t.datetime "current_sign_in_at" 12 t.datetime "last_sign_in_at" 13 t.string "current_sign_in_ip" 14 t.string "last_sign_in_ip" 15 t.datetime "created_at" 16 t.datetime "updated_at" 17 end 18end

###以下にMVCを示します。(関係のある部分のみ)

app/models/user.rb

lang

1class User < ActiveRecord::Base 2 # Include default devise modules. Others available are: 3 # :confirmable, :lockable, :timeoutable and :omniauthable 4 devise :database_authenticatable, :registerable, 5 :recoverable, :rememberable, :trackable, :validatable, :omniauthable 6end

app/views/users/registrations/new.html.erb

lang

1<h2>Sign up</h2> 2 3<%= form_for(resource, as: resource_name, :html => { :multipart => true }, url: registration_path(resource_name)) do |f| %> 4 <%= devise_error_messages! %> 5 6 <div><%= f.label :name, "お名前" %><br /> 7 <%= f.text_field :name, autofocus: true %></div> 8 9 <div><%= f.label :icon, "アイコン" %><br /> 10 <%= f.file_field :icon %></div> 11 12 <div><%= f.label :email, "メールアドレス" %><br /> 13 <%= f.email_field :email %></div> 14 15 <div><%= f.label :password, "パスワード" %><br /> 16 <%= f.password_field :password, autocomplete: "off" %></div> 17 18 <div><%= f.label :password_confirmation, "パスワード(確認用)" %><br /> 19 <%= f.password_field :password_confirmation, autocomplete: "off" %></div> 20 21 <div><%= f.submit "Sign up" %></div> 22<% end %> 23 24<%= render "users/shared/links" %>

app/controllers/users/registrations_controller.rb

lang

1class Users::RegistrationsController < Devise::RegistrationsController 2 3 before_filter :configure_permitted_parameters 4 5 def new 6 super 7 end 8 9 def create 10 super 11 end 12 13 protected 14 def configure_permitted_parameters 15 devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:icon, :name, :email, :password, :password_confirmation) } 16 end 17 18 def sign_up_params 19 devise_parameter_sanitizer.sanitize(:sign_up) 20 end 21 22end

###動作①
name・icon・email・password・password_confirmationを入力し、Sign upをクリックすると「undefined method `name' for nil:NilClass」と怒られます。
![イメージ説明]WIDTH:537
![イメージ説明]WIDTH:600
###動作②
iconにはなにも指定しないでSign upをクリックするとicon以外はきちんと登録されます。
![イメージ説明]WIDTH:505

lang

1 User.all 2 User Load (0.4ms) SELECT `users`.* FROM `users` 3=> [#<User id: 3, name: "山田太郎", icon: nil, email: "yamada@example.com", encrypted_password: "$2a$10$gjpCKyJ/lrAnp.ZsC.HCb.mPWyRprQBfbZ5dYHEaSgq...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2014-11-15 15:37:37", last_sign_in_at: "2014-11-15 15:37:37", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", created_at: "2014-11-15 15:37:37", updated_at: "2014-11-15 15:37:37">]

createメソッドには以下のパラメータが送信されています。

lang

1{"utf8"=>"✓", 2 "authenticity_token"=>"pWAkwJoYBj05BzgSyB0K1ItGcVXE+VkoCtXLoTVPrjw=", 3 "user"=>{"name"=>"山田太郎", 4 "icon"=>#<ActionDispatch::Http::UploadedFile:0x007fbb02c09d00 @tempfile=#<Tempfile:/var/folders/9s/9qds0lbn6n52gbz8b7ykxpgr0000gn/T/RackMultipart20141115-2132-1mqosjq>, 5 @original_filename="icon.jpg", 6 @content_type="image/jpeg", 7 @headers="Content-Disposition: form-data; name=\"user[icon]\"; filename=\"icon.jpg\"\r\nContent-Type: image/jpeg\r\n">, 8 "email"=>"yamada@example.com", 9 "password"=>"[FILTERED]", 10 "password_confirmation"=>"[FILTERED]"}, 11 "commit"=>"Sign up"}

エラーが起きている場所を特定する為にDevise::RegistrationsControllerのcreateメソッド

lang

1 # POST /resource 2 def create 3 build_resource(sign_up_params) 4 5 resource_saved = resource.save 6 yield resource if block_given? 7 if resource_saved 8 if resource.active_for_authentication? 9 set_flash_message :notice, :signed_up if is_flashing_format? 10 sign_up(resource_name, resource) 11 respond_with resource, location: after_sign_up_path_for(resource) 12 else 13 set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format? 14 expire_data_after_sign_in! 15 respond_with resource, location: after_inactive_sign_up_path_for(resource) 16 end 17 else 18 clean_up_passwords resource 19 @validatable = devise_mapping.validatable? 20 if @validatable 21 @minimum_password_length = resource_class.password_length.min 22 end 23 respond_with resource 24 end 25 end

をコピーして当てはめてみると

lang

1resource_saved = resource.save

でエラーが発生していました。
ここの手前のbuild_resource(sign_up_params)でresourceが作られていないのか?と思ったので次の様に中身を見てみるときちんとUserモデルが作成されていました。

lang

1 logger.debug "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" 2 logger.debug "=-=-=-=-= する前 =-=-=-=-=" 3 logger.debug "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" 4 logger.debug resource.inspect 5 6 build_resource(sign_up_params) 7 8 logger.debug "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" 9 logger.debug "=-=-=-=-= した前 =-=-=-=-=" 10 logger.debug "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" 11 logger.debug resource.inspect 12 logger.debug "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" 13 logger.debug "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" 14

lang

1=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 2=-=-=-=-= する前 =-=-=-=-= 3=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 4nil 5=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 6=-=-=-=-= した前 =-=-=-=-= 7=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 8#<User id: nil, name: "山田太郎", icon: #<ActionDispatch::Http::UploadedFile:0x007fd9ee63fe00 @tempfile=#<Tempfile:/var/folders/9s/9qds0lbn6n52gbz8b7ykxpgr0000gn/T/RackMultipart20141116-5573-dj5hix>, @original_filename="icon.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"user[icon]\"; filename=\"icon.jpg\"\r\nContent-Type: image/jpeg\r\n">, email: "yamada@example.com", encrypted_password: "$2a$10$OEukJ2lZMoFv4/G7CnkZyu7m.Mi8ekH56q2b1B4UUjS...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: nil, updated_at: nil> 9=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 10=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

なにかアドバイスを頂けたらと思います。よろしくお願いします。

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

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

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

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

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

guest

回答1

0

Rails 3.1からマルチパートオプションは付けなくてもRails側で自動判別されるはずですが、Railsのバージョンは3.1以上ですか?

投稿2014/11/18 08:00

tmu

総合スコア277

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

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

HirokiShirai

2014/11/20 23:47

回答ありがとうございます。Railsのバージョンは4.1.4です。multipartオプション必要なかったのですね、ありがとうございます。しかしmultipartオプションを外してみましたが結果は変わりませんでした。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

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

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

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問