I'm using a TEXT column in my MySQL database. As the documentation says, it is not possible to set a default value for these columns.
I'm currently using the following code to simulate this behavior:
class Data
before_save lambda {text_column ||= ''}
end
Is there any better, more railis/active_record way to do this?
If you're happy with a HTML5 solution, have you tried a :placeholder attribute on the :text_field?
Also do you really want to stuff a text_field (which captures a small amount of text) into a "text" type column? Did you mean text_area?
If you want the "default value" to actually be stored in the database if the user doesnt input anything then i suggest the following. It's the "Factory" pattern.
Instead of calling "new" on your ActiveRecord model class, you create a "setup" method in your model
def self.setup(params = {})
new(params).tap do |v|
v.text_column = "default value"
# other defaultings
end
end
In your controller instead of calling new on the class you call setup.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With