Skip to content

Instantly share code, notes, and snippets.

@sumitasok
Created April 24, 2012 09:35
Show Gist options
  • Save sumitasok/2478347 to your computer and use it in GitHub Desktop.
Save sumitasok/2478347 to your computer and use it in GitHub Desktop.
accepts_nested_attributes_for - Rails association management using single form submit.
# model file
class User < ActiveRecord::Base
has_many :books
accepts_nested_attributes_for :books, :reject_if => lambda {|book| book[:name].blank? }, :allow_destroy => true
end
# :reject_if => it passes the whole hash passed from browser with book details into this Proc(lambda) and iterates over each book hash. The book record is not created if the condition given in the lambda block is satisfied.
# :allow_destroy => if set to true, then the book record that was passed from browser, while submitting User form, with a key-value pair :_destroy => 1 (or '1' or true or "true") will be destroyed
# controller file
class UsersControler < ActionController::Base
def new
@user = User.new
@books = []
@books << @user.books.new
end
def edit
@user = User.find(params[:id])
@books = @user.books
end
end
/ view file
= form_for @user do |form|
= form.text_field :name
= form.fields_for :books, @books do |book_name|
= book_form.text_field :name
= book_form.hidden_field :_destroy, :class => 'destroy-field'
/ this hidden_field should be given a value of ( 1 or "1" or true or 'true' ) if this record has to be destroyed.
@books can either be @user.books if this is an User#edit form
or can be @user = User.new; @user.build_books n times
so that much times of form fields will be displayed of books belonging to user.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment