In a Rails ActiveRecord model, is using after_initialize callbacks a very bad idea?
Most uses of after_initialize
can be (and SHOULD be) replaced with defaults on the corresponding database columns. If you're setting the property to a constant value, you may want to look into this as an alternative.
EDIT: if the value isn't constant, a call to has_attribute?(:name)
will guard against this error - ActiveModel::MissingAttributeError occurs after deploying and then goes away after a while
ActiveModel::MissingAttributeError (can't write unknown attribute `user_id`)
You'll need to add a user_id
column to your comments
table. The belongs_to
requires this. You're also going to need a post_id
column, and user_id
for your posts
table to.
You can customise the column name, but the convention is to use the format parent_table_id
.
Here's the key quote, from the docs:
Associations are implemented using macro-style calls, so that you can
declaratively add features to your models. For example, by declaring
that one model belongs_to another, you instruct Rails to maintain
Primary Key-Foreign Key information between instances of the two
models, and you also get a number of utility methods added to your
model.
This means, for example, if your first user has an id of 1
, all of their comments and posts will have a user_id
value of 1
, which does the actual tying together of the records.
Here's an example migration with the relevant line included:
def change
create_table :comments do |t|
...
t.belongs_to :user, index: true
...
end
end
Does that make sense? Let me know if you've any questions and I can update as needed :)
ActiveModel dymamic methods in instance objects
you can add methods with singleton_class.module_eval
def initialize(attributes = {})
set_default_attributes!
@attributes.each do |key,value|
singleton_class.module_eval do
define_method(key) { self.attributes[key] } unless method_defined? key
define_method("#{key}=") { |new_value| self.attributes[key] = new_value } unless method_defined? "#{key}="
end
end
@attributes.merge!(attributes.symbolize_keys)
@new_record = true
end
Related Topics
Optimization for Finding Perfect-Square Algorithm
How to Run Shell Commands on Server in Capistrano V3
Rake VS. Thor for Automation Scripts
Why Doesn't 'User Installation Directory' Match with the Ruby Version
Troubleshooting Ssl Certificates, Ruby, MAC Os X Yosemite
What Is the &: of &:Afunction Doing
How to Find Where Gem Files Are Installed
How to Step Out of a Loop with Ruby Pry
Rails: Convert Utc Datetime to Another Time Zone
What Is Mattr_Accessor in a Rails Module
Measure and Benchmark Time for Ruby Methods
Mountain Lion - Libxml & Nokogiri
Undefined Method 'Devise' for User