Notes posted by edavey
RSS feed
can be useful to achieve attr_reader effect
e.g.
class Account < ActiveRecord::Base def credit(amount) self.write_attribute(:balance, self.balance + amount) self.save! end def balance=(value) raise "You can't set this attribute. It is private." end end
this allows fred.account.credit(5) whilst raising an error on fred.account.balance = 1000


options_for_select further example (using a collection and with a default value)
In this example, we are editing a collection of region records, each with its own select list of countries. (Region belongs_to :country.) If the region doesn’t have a country associated, then we want a default message of “unassigned”. Of course, if the region does have a country associated then we want that country displayed:
<% name = "region[" + region.id.to_s + "][country_id]" %> <% id = "region_" + region.id.to_s %> <%= select_tag(id, options_for_select([["unassigned" , "0" ]] + Country.to_dropdown, region.country_id),
{:name => name} ) %> This give us:
<select id="region_3" name="region[3][country_id]"> <option value="0">unassigned</option> <option selected="selected" value="12">England</option> </select>
NB: we’re using the handy acts_as_dropdown plugin (http://delynnberry.com/projects/acts-as-dropdown/) but we could just as easily prepare the select list with map / collect as above.

:only, :except and passing in multiple parameters
To specify that the filter should be applied to or excluded from given controller actions, use the :only and :except parameters. To pass in multiple controller actions use an array:
before_filter :authorize, :except => [:index, :show] before_filter :authorize, :only => :delete