views:

33

answers:

1

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 restrictions 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.

+1  A: 

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.

Damien MATHIEU
Shouldn't it be :default => false in the first code block?
DR
Well it could be any value you want. It's the default value. So you put whatever default value you want for this field.
Damien MATHIEU
Sorry, I don't get it :) Can you elaborate a little bit? For example: Setting the database default value, has to done anyway according to my question, so I don't understand why this is one of two different ways? And setting predefined to true in my model would take effect in every other situation, too, not just in my rake task...
DR
You define a default value, either in the MySQL database, either in your model. So when you don't define any value, it's the default one that'll be used.Yeah, there won't be any difference between your rake tasks or any other situation. It's a default value. It's default everywhere.
Damien MATHIEU
OK, I understand. But my question was, how can I *temporarily* change that default value?
DR