简体   繁体   中英

Understanding Create in rails

##==================================User Model====
class User < ActiveRecord::Base
  validates :name,presence: true ,message: "Name can't be empty."
end

##===========================Migration==============
class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name ,null: false
   end
  end
end

##==================================Schema.rb================
ActiveRecord::Schema.define(version: 20151030131541) do
  create_table "users", force: :cascade do |t|
    t.string "name", null: false
  end
end

##==========================Rails console==============
irb(main):009:0> User.create
   (0.2ms)  begin transaction
  SQL (0.5ms)  INSERT INTO "users" DEFAULT VALUES
   (139.6ms)  commit transaction
=> #<User id: 4, name: nil>
irb(main):010:0>

I am using sqlite3 for database. Even though I have validation in model and NOT NULL condition in migration but still it is creating User with name as :nil , can somebody please explain how is this possible ?

It's not actually creating the record. Per the Rails docs :

Tries to create a new record with the same scoped attributes defined in the relation. Returns the initialized object if validation fails.

The last sentence is the key...returns the initialized object. It's an invalid object and not yet added to the database.

Try User.create! since the bang method raises an exception instead of an invalidated object.

Your validator is incorrect. It should be:

validates :name, presence: { message: "can't be empty." }

The text "Name" is added for you.

So:

Try rolling back your migration and re-migrating from the terminal:

rake db:rollback
rake db:migrate

Then reload your console and try:

user = User.create

user.id
#=> nil #Shows it has not saved

user.errors.full_messages

#=> ["Name can't be empty."]

User.count
#   (0.2ms)  SELECT COUNT(*) FROM "users"
#=> 0

Which is the behaviour I get when replicating your project and fixing your validation issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM