How can I tell Rails to completely ignore one specific column when INSERTing using the save method? I want the database's default value to be used, but currently Rails is setting it to NULL.
Andre Santos wrote:
How can I tell Rails to completely ignore one specific column when INSERTing using the save method? I want the database's default value to be used, but currently Rails is setting it to NULL.
I don't believe you can tell Rails to ignore a column on a save (I don't see any such options in the API docs).
When you do a <Model_name>.new it'll put in any default values for the attributes at that time. If you don't alter those attributes it should still have the default values in there.
Are you altering the attributes in some way but want to reset them back to their defaults? If so I believe the only way to "reset" them is to set the values of those attributes manually (having saved off the default values before they were altered somewhere).
Rails sets the database default value when you create a new instance of the object, that's done by attributes_from_column_definition
# Initializes the attributes array with keys matching the columns from the linked table and # the values matching the corresponding default value of that column, so # that a new instance, or one populated from a passed-in Hash, still has all the attributes # that instances loaded from the database would. def attributes_from_column_definition self.class.columns.inject({}) do |attributes, column| attributes[column.name] = column.default unless column.name == self.class.primary_key attributes end end
which in turn is called by AR::Base.new. Is your code assigning nils by hand?
-- fxn
This is the column, database is PostgreSQL:
codigo BIGINT UNIQUE NOT NULL DEFAULT nextval('customers_codigo_seq'),
It's like an auto-incrementing column in MySQL.
Currently, I'm not setting it to anything, Rails is setting it to NULL, and PostgreSQL complains that:
null value in column "codigo" violates not-null constraint : INSERT INTO customers ...
It needs to be DEFAULT, without quotes, or not sent at all.
Thank you!
I wrote a small stored procedure that sets the codigo column when it's NULL on INSERT. There's probably a much better way to solve this problem, but I haven't figured it out yet. Any ideas?
Anybody using sequences with PostgreSQL?
Andre Santos wrote: