Good notes posted by railsmonk
RSS feedThis method will still rewrite all the values of the table
Even if you update only a small boolean flag on your record, update_attribute will generate an UPDATE statement that will include all the fields of the record, including huge BLOB and TEXT columns. Take this in account.
Works with URLs too!
You can use it for web urls as well:
path, file = File.split('/uploads/art/2869-speaking-of-pic.jpg') p path # => "/uploads/art" p file # => "2869-speaking-of-pic.jpg"
And you can also use join, to merge url back from the components:
path = File.join(["/uploads/art", "2869-speaking-of-pic.jpg"]) p path # => "/uploads/art/2869-speaking-of-pic.jpg"
Using #join and #split for operations on files and path parts of the URLs is generally better than simply joining/splitting strings by ‘/’ symbol. Mostly because of normalization:
File.split('//tmp///someimage.jpg') # => ["/tmp", "someimage.jpg"] '//tmp///someimage.jpg'.split('/') # => ["", "", "tmp", "", "", "someimage.jpg"]
Same thing happens with join.
:prefix option
Be aware!
By default, if you do select_month(Date.today, :field_name => ‘start’) it will generate select tag with name “date[start]”. If you want it to be something other than date[], add :prefix option, like this:
select_month(Date.today, :field_name => 'start', :prefix => 'timer')
This will render select tag with name “timer[start]”.
Taken from sources of name_and_id_from_options method.
Example of composed_of composition class implementation
If we have following code in model:
composed_of :temperature, :mapping => %w(celsius)
Then our composition class can be this:
class Temperature def initialize(celsius) @celsius = celsius end # This method is called by ActiveRecord, when record is saved. # Result of this method will be stored in table in "celsius" field, # and later when the record is loaded again, this will go to # our Temperature#new constructor. def celsius @celsius end # This is example of method that we can add to make this composition useful. def farenheit @celsius * 9/5 + 32 end end
has_many :through
It’s is recommended to use has_many :through association instead of has_and_belongs_to_many. has_many :through is better supported and generally easier to work with once you grasp the idea.
Method description from Rails 2.0
If text is longer than length, text will be truncated to the length of length (defaults to 30) and the last characters will be replaced with the truncate_string (defaults to “…”).
Examples
truncate("Once upon a time in a world far far away", 14) # => Once upon a... truncate("Once upon a time in a world far far away") # => Once upon a time in a world f... truncate("And they found that many people were sleeping better.", 25, "(clipped)") # => And they found that many (clipped) truncate("And they found that many people were sleeping better.", 15, "... (continued)") # => And they found... (continued)