I'm trying to find the best way to set default values for objects in Rails.
The best I can think of is to set the default value in the new
method in the controller.
Does anyone have any input if this is acceptable or if there's a better way to do it?
In order to define a default value for a parameter, we use the equal sign (=) and specify a value to which a local variable inside the method should reference. Thus, parameters with a default value allow us to not pass any arguments and have a working method that works with predefined data.
Adding Default Arguments Default arguments are easy to add, you simply assign them a default value with = ("equals") in the argument list. There's no limit to the number of arguments that you can make default. Let's take a look at the different ways we can call this method: greeting # > Hello, Ruby programmer.
A column's default value is part of its definition, but can be modified separately from other aspects of the definition. To change a default value, use ALTER col_name SET DEFAULT : ALTER TABLE mytbl ALTER j SET DEFAULT 1000; Default values must be constants.
How do I remove a column from a table in Ruby on Rails? remove_column :table_name, :column_name, :type Removes column, also adds column back if migration is rollbacked. Note: If you skip the data_type, the migration will remove the column successfully but if you rollback the migration it will throw an error.
"Correct" is a dangerous word in Ruby. There's usually more than one way to do anything. If you know you'll always want that default value for that column on that table, setting them in a DB migration file is the easiest way:
class SetDefault < ActiveRecord::Migration def self.up change_column :people, :last_name, :type, :default => "Doe" end def self.down # You can't currently remove default values in Rails raise ActiveRecord::IrreversibleMigration, "Can't remove the default" end end
Because ActiveRecord autodiscovers your table and column properties, this will cause the same default to be set in any model using it in any standard Rails app.
However, if you only want default values set in specific cases -- say, it's an inherited model that shares a table with some others -- then another elegant way is do it directly in your Rails code when the model object is created:
class GenericPerson < Person def initialize(attributes=nil) attr_with_defaults = {:last_name => "Doe"}.merge(attributes) super(attr_with_defaults) end end
Then, when you do a GenericPerson.new()
, it'll always trickle the "Doe" attribute up to Person.new()
unless you override it with something else.
Based on SFEley's answer, here is an updated/fixed one for newer Rails versions:
class SetDefault < ActiveRecord::Migration def change change_column :table_name, :column_name, :type, default: "Your value" end end
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