Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord not saving any attributes, saving default values

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?

like image 611
Sam Stern Avatar asked Jul 09 '13 05:07

Sam Stern


People also ask

What does ActiveRecord base do?

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 in Ruby on Rails?

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.

What is ActiveRecord?

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.


1 Answers

attr_accessor is overriding the rails attributes. Try removing it and it should work.

like image 194
Darren Coxall Avatar answered Sep 25 '22 00:09

Darren Coxall