I have a User
model with some attributes, call them foo
and bar
. So my model looks like this:
class User < ActiveRecord::Base
attr_accessor :foo, :bar
end
Then I do the following:
user = User.new
user.foo = "123"
user.save!
And my development log shows:
INSERT INTO "users" DEFAULT VALUES RETURNING "id"
Then if I go into the Rails console and do User.first
I get something like:
#<User id: 4, foo: nil, bar: nil>
I am using Postgres and I am having no trouble saving other models to the database, why is my User
model saving default values?
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module...
What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that you can use to check your models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format, and many more.
attr_accessor
is overriding the rails attributes. Try removing it and it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With