method
with_options
![Wide documentation Importance_3](https://d2vfyqvduarcvs.cloudfront.net/images/importance_3.png?1349367920)
with_options(options)
public
An elegant way to refactor out common options
with_options :order => 'created_at', :class_name => 'Comment' do |post| post.has_many :comments, :conditions => ['approved = ?', true], :dependent => :delete_all post.has_many :unapproved_comments, :conditions => ['approved = ?', false] post.has_many :all_comments end
Can also be used with an explicit receiver:
map.with_options :controller => "people" do |people| people.connect "/people", :action => "index" people.connect "/people/:id", :action => "show" end
Register or
log in
to add new notes.
Pilaf -
February 23, 2009
himn1 -
October 7, 2010
kwerle -
May 18, 2012
![Default_avatar_30](https://www.gravatar.com/avatar/1eaf88725aac486f742ae64a8abe0f6c?default=http://apidock.com/images/default_avatar_30.png&size=30)
6 thanks
Nested with_options
You can nest with_options blocks, and you can even use the same name for the block parameter each time. E.g.:
class Product with_options :dependent => :destroy do |product| product.with_options :class_name => 'Media' do |product| product.has_many :images, :conditions => {:content_type => 'image'} product.has_many :videos, :conditions => {:content_type => 'video'} end product.has_many :comments end end
![Default_avatar_30](https://www.gravatar.com/avatar/2c2bc4e931e544fbbd8b28f6b04cd2f1?default=http://apidock.com/images/default_avatar_30.png&size=30)
0 thanks
![Default_avatar_30](https://www.gravatar.com/avatar/0b15561003904626e2542dc867aefbba?default=http://apidock.com/images/default_avatar_30.png&size=30)
0 thanks
Beware nested with_options clobbers!
Careful:
with_options :foo => :bar do |something| something.with_options :foo => :baz do |inner| what_is(:foo) end end
:foo will be :baz. It will not be [:bar, :baz], for example.
This bit me when trying to do nested with_options for validation where both had :if => something.