11
9

More than 5 years have passed since last update.

[Rails]データベースに保存する処理でNomethoderror undefined methodがでた

Last updated at Posted at 2014-10-24

Railsで、データを保存しようとしたところ、以下のエラーが(全文ではないです)。

NoMethodError in TodosController#add

undefined method `todo' for #<Todo:0x007fc52bfe8830>

Application Trace
app/controllers/todos_controller.rb:20:in `add'

この20行目が、以下のコメントした箇所でした。

todos_controller.rb
class TodosController < ApplicationController
    protect_from_forgery with: :null_session

    def add
        todo_instance = {
            user_id: params[:todos][:user_id],
            completion: params[:todos][:completion],
            content: params[:todos][:content],
        }

            Todo.create(todo_instance) # ←ここがエラーを起こしていた箇所。
        render json: "success".to_json  
    end
end

で、何故実行されないのか色々調べていましたが。。

結論からいうと、モデルに、存在しないカラムのvalidationがはいっていたからでした。

todo.rb
class Todo < ActiveRecord::Base
  belongs_to :user
  validates :todo, presence: true # ←この1行がエラーを起こしていた・・・。
  validates :user_id, presence: true
end

エラー見ると、

undefined method `todo&#39; for #&lt;Todo:0x007fc52bfe8830&gt;

とあるので、そういうことか、とあとになって気づきました。。

自分以外の人が作ったモデルだったのと、
僕が、人が作った、すでにすべてが揃っているRailsしかさわったことがなかったので、基礎が抜け落ちていました。。

あとエラーをちゃんと見れてない。よく見ようという話でした。

11
9
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
11
9