Skip to content

Instantly share code, notes, and snippets.

@inem
Created February 8, 2009 08:44
Show Gist options
  • Save inem/60310 to your computer and use it in GitHub Desktop.
Save inem/60310 to your computer and use it in GitHub Desktop.
#Rails 2.3 features
User.admins.first.try(:address).try(:reset)
#--------------------------------------------
render :partial => 'articles/article', :locals => { :article => @article }
#--->
render @article
#-------------------------------------------
default_scope :order => 'created_at DESC'
Article.with_exclusive_scope { find(:all) }
#-------------------------------------------
#http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes
#--------------------------------------------------------------------------
class Person < ActiveRecord::Base
validates_presence_of :name
has_many :children, :class_name => 'Person'
accepts_nested_attributes_for :children
# can also be used on has_one etc.. associations
end
#---------------------------------------------------------------------
# Add a new child to this person
@person.children_attributes = { 'new_1' => { :name => 'Son' } }
@person.children #=> [ <#Person: name: 'Son'> ]
@person.children.clear
# Add two new children to this person
@person.children_attributes =
{ 'new_1' => { :name => 'Son' }, 'new_2' => { :name => 'Daughter' } }
@person.save
@person.children #=> [ <#Person: name: 'Son'>, <#Person: name: 'Daughter'> ]
# Edit the son (assuming id == 1)
@person.children_attributes = { '1' => { :name => 'Lad' } }
@person.save
#=> the son's name is now 'Lad'
# Edit the daughter (id == 2) and add a new offspring
@person.children_attributes =
{ '2' => { :name => 'Lassie' }, 'new_1' => { :name => 'Pat' } }
@person.save
#=> the daughter's name is now 'Lassie' and there's a new offspring called 'Pat'
# Remove Pat (id = 3), we don't like him/her
@person.children_attributes = { '3' => { '_delete' => '1' } }
@person.save
#=> Pat is now deleted
#------------------------------------------------
<% form_for @person do |person_form| %>
<%= person_form.label :name %>
<%= person_form.text_field :name %>
<% person_form.fields_for :children do |child_form| %>
<%= child_form.label :name %>
<%= child_form.text_field :name %>
<% unless child_form.object.new_record? %>
<%= child_form.checkbox '_delete' %>
<%= child_form.label '_delete', 'Remove' %>
<% end %>
<% end %>
<%= submit_tag %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment