Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to simulate default value for TEXT column using Ruby on Rails?

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?

like image 292
Simon Hürlimann Avatar asked Oct 31 '25 07:10

Simon Hürlimann


1 Answers

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.

like image 199
Aditya Sanghi Avatar answered Nov 02 '25 20:11

Aditya Sanghi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!