Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent NULL for active record INSERT?

I have a database view with a computed column that I'm using to back a Rails model. The INSERT INTO statement generated by model.create tries to set that column to null, which causes the database to complain and the record not to be created. I know :attr_readonly can be used to have the column not be specified in UPDATEs, but is there a way to tell ActiveRecord that it shouldn't specify it for INSERTs either?

like image 479
Shea Levy Avatar asked Sep 15 '26 06:09

Shea Levy


1 Answers

You could: Remove the attribute manually from the object before you create it.

  before_create(:remove_attribute)

  private

  def remove_attribute
    @attributes.delete('unwanted_attribute')
  end

Beware that this removes the attribute completely from the current object. If you need to access the removed attribute after having created the record, the record will need to be reloaded.

like image 61
Michael Durrant Avatar answered Sep 17 '26 20:09

Michael Durrant