Unit-IV; Professional Sales Representative (PSR).pptx
Getting started with Rails (4), Season 2
1. ROR Lab. Season 2
- The 4th Round -
Getting Started
with Rails (4)
August 11, 2012
Hyoseong Choi
ROR Lab.
2. A Blog Project
Post
ny
on
a
m
separate form nested form
e
to form_for
to
ne
m
an
o
y
Comment Tag
form_for fields_for
ROR Lab.
3. Generating the 3rd
Model : Tag
$ rails generate model tag
name:string
post:references
Migration file
Model Class : db/migrate/xxxx_create_tag.rb
: app/models/tag.rb
Tag tags
$ rake db:migrate
belongs_to :post post_id :integer
post:references
ROR Lab.
4. Nested Attributes
• save the child object through the parent
object
• Off, by default
• switch “On”, by calling
#accepts_nested_attributes_for
• an attribute writer automatically defined on the parent
model
• :autosave option automatically enabled
http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
ROR Lab.
5. Building a Multi-
Model Form ✔
class Post < ActiveRecord::Base
attr_accessible :content, :name, :title, :tags_attributes
validates :name, :presence => true
validates :title, :presence => true,
:length => { :minimum => 5 }
has_many :comments, :dependent => :destroy
has_many :tags
✔
accepts_nested_attributes_for :tags, :allow_destroy => :true,
:reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end ✔
multi-model form or nested form or form in form
ROR Lab.
7. build vs new
• new ➞ for Class
ex) post = Post.new
• build ➞ for association proxy
ex) comment = post.comments.build
✓ automatic setting its foreign key for the
new child object with patient object id
ROR Lab.