How to temporarily change the default value of column?
I have a model which contains many predefined rows (> 100) and also can be edited by the user. I want to distinguish between pre-defined and user-added rows.
Because the database will be edited by a third-party application, too, I want to be on the safe side and set the default value for predefined
to false
in the database schema, because setting it to true will lead to serious re开发者_如何转开发strictions on the row (i.e. it can never be deleted)
On the other hand the install script which creates the > 100 predefined rows now has to specify predefined = true
for every row, which clutters the script.
It's not that bad, but if there's a simple way to change the default way from Rails it would make my script look more friendly.
In other words: I want to write this:
MyModel.create(:data => "value")
but what I want to happen is this:
MyModel.create(:data => "value", :predefined = true)
Is this possible?
EDIT: This is only an examply, actually there are some more columns I have to set differently for predefined columns.
You could do it two different ways :
In your migrations :
t.column :boolean :string, :default => true
It defines the default value to true directly in the database. When you change it, you have to create a new migration.
In your model :
def before_create
predefined = true if predefined.nil?
end
It defines the value to "true" unless you already defined it to something else. You can change the value just by changing it in the model.
精彩评论