January 2010
13 posts
2 tags
Update with a touch
From Rails 2.3.3 on, you can update the updated_at time stamp of an instance with touch:
user.updated_at #=> "Wed Jan 27 23:29:22 +1300 2010"
user.touch
user.updated_at #=> "Wed Jan 27 23:30:08 +1300 2010"
You can also update associated parent models by specifying the :touch option on the relation:
class Organization < ActiveRecord::Base
has_many :users
end
class User <...
3 tags
nil?, empty? and blank?
In Ruby, you check with nil? if an object is nil:
article = nil
article.nil? # => true
empty? checks if an element - like a string or an array f.e. - is empty:
# Array
[].empty? #=> true
# String
"".empty? #=> true
Rails adds the method blank? to the Object class:
An object is blank if it‘s false, empty, or a whitespace string. For example, “”, ”...
3 tags
Date manipulation
You can add or subtract days or month from a Date object:
+(n): add n number of days
-(n): subtract n number of days
>>(n): add n number of months
<<(n): subtract n number of months
Here are some examples:
$ irb
>> date = Date.today # => #<Date: ...>
>> date.to_s
=> "2010-01-26"
>> tomorrow = date + 1 # => #<Date: ...>
>>...
3 tags
Calculate the last day of the month
With Date.civil(y, m, d) (or its alias .new(y, m, d)), you can create a new Date object. The values for day (d) and month (m) can be negative in which case they count backwards from the end of the year and the end of the month respectively.
>> Date.civil(2010, 02, -1)
=> Sun, 28 Feb 2010
>> Date.civil(2010, -1, -5)
=> Mon, 27 Dec 2010
See the documentation on civil method.
3 tags
Customize error_messages_for
Did you know that error_messages_for takes a whole bunch of options for customization?
<%= error_messages_for :employee,
:class => "flash error",
:header_tag => "h4",
:header_message => "Sorry, the employee couldn't be created" %>
The options for the <div> that is returned include :header_tag, :id,...
2 tags
Named Scopes: add named finders to your...
With a ‘named scope’, you can add reusable ActiveRecord find methods to your model.
So instead of writing this in your controller, every time you need it…
User.find(:all, :conditions => { :active => true }, :order => "first_name, last_name ASC")
…you can add a named scope to your User model that represents this find statement:
class User <...
2 tags
Split a string with 'split'
To split a string at a a given delimiter, use the split method. The default delimiter is the space ’ ‘, and an array of the words is returned.
"A string to split".split # => ["A", "string", "to", "split"]
"tag1,tag2,tag3".split(',') # => ["tag1", "tag2", "tag3"]
Ruby Documentation.
3 tags
Find or Create an object in one command
The find_or_create_by_ dynamic finder will return the object if it already exists and otherwise creates it, then returns it:
# No 'Summer' tag exists
Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
# Now the 'Summer' tag does exist
Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
There’s also a find_or_initialize_by finder if...
3 tags
Console tip: retrieve the last return value with...
In IRB you can retrieve the last return value from a command by using the underscore _ sign:
$ irb
>> 2*3
=> 6
>> _ + 7
=> 13
>> _
=> 13
This also works in the Rails console:
$ script/console
>> User.first
=> #<User id: 7, first_name ...
>> user = _
=> #<User id: 7, first_name ...
>> user
=> #<User id: 7, first_name ...
This is...
3 tags
Dynamic attribute-based finders
Dynamic attribute-based finders are a cleaner way of getting objects by simple queries without turning to SQL. They work by appending the name of an attribute to find_by_, find_last_by_, or find_all_by_, so you get finders like Person.find_by_user_name, Person.find_all_by_last_name, and Payment.find_by_transaction_id.
So, instead of writing
Person.find(:all, :conditions => ["last_name =...
3 tags
Inject your enumerables
Every class that inherits from Enumerable - such as Array or Hash f.e. - inherits a method called inject.
inject combines the elements of the object it is called on (an Array or Hash f.e.) by applying the given block to an accumulator value and each element in turn.
Here are some examples:
# Sum some numbers
(5..10).inject {|sum, n| sum + n } #=> 45
# Multiply some...
3 tags
Disabling input fields on a form based on a...
You may know about the :disabled option for form elements such as buttons, text-fields etc:
submit_tag "Pay", :disabled => true
Did you know, you can pass any boolean expression as a value?
submit_tag "Pay", :disabled => @cart.empty?
(via Using conditions in Form Helpers of Rails)
4 tags
Shorter render statement for partials
From Rails 2.3 on
render :partial => "p", :locals => { :x => 1 }
can be written as
render "p", :x => 1
(via DHH)