ActiveRecord not saving any attributes, saving def

2020-06-03 03:28发布

问题:

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?

回答1:

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