Tag Archives: ActiveRecord

Tip: Return True for Model Hooks

Everyone loves before_create and before_save. Recently it came in very handy for logging hits to objects. If the user is logged in, I want to store the user’s full name and the user’s type, otherwise, keep those null. So I added this to my PostHit model:
 
def before_create
if self.user
self.user_name = […]

Chaining Create Methods to an Object Instance

In my Rails controllers, I have a lot of this:
 
@project = Project.find(params[:project])
if @project
@project_product = @project.project_products.create(params[:project_product])
if @project_product.valid?
# Do something with success
else
# Do something with error
end
else
# Do something with error
end
 
The thing that I don’t like about that style is that the […]