2. Content
● Rails Getter / Setter
● Nested Attributes
● Dynamical using getter/setter for
nested_attributes
● Custom setter of nested_attributes
3. Rails Getter/Setter
● A setter
● A getter
def xfunction= value
@xfunction = value
end
def xfunction
@xfunction
end
4. Rails Getter/Setter
● Rails default using a pairs of getter/setter is
○ read_attribute :xattribute
○ write_attribute :xattribute, xvalue
○ -> attr_accessible, attr_accessor
● 2 methods is getter/setter for attr_accessor
○ attr_reader
○ attr_writer
● Use which method that you need, then you
can overwrite the other one by yourself
without changing the Rails architecture.
5. nested_attributes
● Rails nested_attributes is
○ Fast
○ Strong in handle sets of objects
● But, it is
○ Hard to handle the values in sets of objects
○ Weak in security if use addition methods like
call_backs or just some validation on views
6. nested_attributes
● Rewrite setter of it
● Should not rewrite getter
def xnested_attributes=(values)
# Do some addition here
# Raise errors if needed
assign_nested_attributes_for_collection_association :xnested,
values
end
7. Dynamical using
● When you must load or initialize all sets of
objects inside model
● When you have a set of objects that not
really like [parent-childrens]
○ nested_attributes can’t work if parent isn’t persisted
○ associations is very hard to handle
○ Very weak security when you just want to load a
specific object
=> custom setter of nested_attributes
8. Custom setter
● Middle object
○ use [nested_attributes setter + attr_accessor]
○ Load or create parent, raise errors and [next] if failed
● Children object
○ use [attr_writer + instance reader]
● Parent object
○ use [instance reader]
○ Call middle object with [attr_accessor]
9. Pros & Cons
● Cons
○ 3 classes must be modified
○ A bit complicated to understand the logic and flow
● Pros
○ Only 1 block of logic
○ Strongly on incorrect params
○ Fast
○ Follow Rails architecture