为什么这个对象没有被保存在数据库中?
问题描述:
作为一个练习,我试图用rails-api gem来构建一个API,但是我不明白这个代码有什么问题。 有没有我没有看到的错误? 我使用的铁轨4.2.4为什么这个对象没有被保存在数据库中?
型号:
class Todo < ActiveRecord::Base
validates :title, :presence => true, length: { minimum: 3, maximum: 32 }
validates :content, :presence => true, length: { minimum: 60, maximum: 160 }
end
控制器:
class TodosController < ActionController::API
def create
@todo = Todo.new(todo_params)
if @todo.valid?
if @todo.save
render json: @todo, status: :created, location: @todo
else
render json: @todo.errors, status: :unprocessable_entity
end
end
end
private
def todo_params
params.require(:todo).permit(:title, :content)
end
end
规格:
require 'rails_helper'
RSpec.describe TodosController, type: :controller do
describe "#create" do
context "when JSON format" do
describe "#create" do
subject{
post :create, {
:format => :json,
:todo => {
:title => 'the title',
:content => 'the content which is bigger than the title'
}
}
}
its(:status) { should == 200 } # OK
it "saves the todo" do
subject
Todo.all.count.should == 1
end
end
end
end
end
错误运行此命令“rspec的投机/”:
F................
Failures:
1) TodosController#create when JSON format #create saves the todo
Failure/Error: Todo.all.count.should == 1
expected: 1
got: 0 (using ==)
# ./spec/controllers/todos_controller_spec.rb:21:in `block (5 levels) in <top (required)>'
答
在你创建的方法,如果模型无效,那么代码将永远不会达到render
语句。在这种情况下,导轨将假定状态为:ok
并呈现默认模板。
尝试重构您的代码,以便它总是会遇到这种情况。
def create
@todo = Todo.new(todo_params)
if @todo.save # will be false if the save didn't work
render json: @todo, status: :created, location: @todo
else
render json: @todo.errors, status: :unprocessable_entity
end
end
检查你正在渲染的错误? :) – sevenseacat
我的问题解决了,但我很好奇,我该如何检查错误? – NeimadTL
@ Neimad971你可以使用'byebug' gem并在你调用它并调试你的代码的地方停止执行。 – miligraf