Created
October 25, 2011 07:36
-
-
Save Amitesh/1311731 to your computer and use it in GitHub Desktop.
Nested Model and It's step to make it happen in rails 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
How to setup netsed model in Rails 3 | |
======================================== | |
CREATE TABLE `books` ( | |
`id` int(11) NOT NULL AUTO_INCREMENT, | |
`title` varchar(255) DEFAULT NULL, | |
`description` text, | |
`imported_from` varchar(255) DEFAULT NULL, | |
`created_at` datetime DEFAULT NULL, | |
`updated_at` datetime DEFAULT NULL | |
PRIMARY KEY (`id`) | |
) | |
CREATE TABLE `books_isbns` ( | |
`id` int(11) NOT NULL AUTO_INCREMENT, | |
`isbn` varchar(255) DEFAULT NULL, | |
`book_id` int(11) DEFAULT NULL, | |
`created_at` datetime DEFAULT NULL, | |
`updated_at` datetime DEFAULT NULL, | |
PRIMARY KEY (`id`) | |
) | |
- Create models | |
class Book < ActiveRecord::Base | |
# Book ISBN | |
has_many :books_isbn, :dependent => :destroy | |
accepts_nested_attributes_for :books_isbn, :allow_destroy => true | |
attr_accessible :books_isbn_attributes | |
end | |
class BooksIsbn < ActiveRecord::Base | |
belongs_to :book | |
end | |
- Controller | |
> Input Page or Get Action | |
def add | |
@book = Book.new() | |
@book.books_isbn.build | |
end | |
def save | |
begin | |
Book.transaction do | |
@book = Book.new(params[:book]) | |
@book.save ? redirect_to(book_path(@book)) : render(:action => :new) | |
end # transaction end | |
rescue Exception => e | |
Rails.logger.info "Problem in creating book : #{ e.message }" | |
end | |
# render... | |
end | |
- In view | |
<%= form_for(@book, :url => book_save_details_path(:id => @book), :html =>{:multipart => true, :method => :post}) do |f| %> | |
<%= f.fields_for :books_isbn do | isbn | %> | |
<%= isbn.label :isbn %> | |
<%= isbn.text_field :isbn %> | |
<% end %> | |
<% end %> | |
- Generated field name | |
book[books_isbn_attributes][0][isbn] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment