- virtual attribute
++++++++++++++++++++++++++++
NEW/CREATE
++++++++++++++++++++++++++++
*controller
[NEW]
1. Build object
@customer.addresses.build
------------
*view
[MAIN]
1. form_for
2. Make div of object which would have many instances (ie:addresses)
#addresses
= render :partial => 'address', :collection => @customer.addresses
= add_address_link "Add Address"
[PARTIAL]
new method:
<% new_or_existing = task.new_record? ? 'new' : 'existing' %>
<% prefix = "project[#{new_or_existing}_task_attributes][]" %>
<% fields_for prefix, task do |task_form| -%>
Task: <%= task_form.text_field :name %>
<%= link_to_function "remove" , "$(this).up('.task').remove()" %>
<% end -%>
---
1. fields_for
- fields_for "customer[address_attributes][]", address do |af|
2. Add link to remove
= link_to_function "Remove","$(this).up('.tablecontainer').remove()"
**tablecontainer will be removed
--------------
*helper
1. For adding another class instance
def add_address_link(name)
link_to_function name do |page|
page.insert_html :bottom, :addresses, :partial => 'address', :object => NinAddress.new
end
end
========================
insert_html(position, id, *options_for_render)
Inserts HTML at the specified position relative to the DOM element identified by the given id.
position may be one of:
:top: HTML is inserted inside the element, before the elementës existing content.
:bottom: HTML is inserted inside the element, after the elementës existing content.
:before: HTML is inserted immediately preceding the element.
:after: HTML is inserted immediately following the element.
Note:
- use ':bottom' if inserting new table
#div_name
= render...
= add_link
- use ':after' if inserting new row
%tr#div_name
= render ...**
= add_link
** render starts with %tr as well
==========================
--------------
*model
1. define virtual attribute
new:
def new_task_attributes=(task_attributes)
def address_attributes=(address_attributes)
address_attributes.each do |attributes|
addresses.build(attributes)
end
end
---------------
+++++++++++++++++++++++++++
EDIT/UPDATE
+++++++++++++++++++++++++++
*controller
def edit
@project = Project.find(params[:id])
end
def update
params[:project][:existing_task_attributes] ||= {}
@project = Project.find(params[:id])
if @project.update_attributes(params[:project])
flash[:notice] = "Successfully updated project and tasks."
redirect_to project_path(@project)
else
render :action => 'edit'
end
end
*model
validates_associated :tasks
after_update :save_tasks
def existing_task_attributes=(task_attributes)
tasks.reject(&:new_record?).each do |task|
attributes = task_attributes[task.id.to_s]
if attributes
task.attributes = attributes
else
tasks.delete(task)
end
end
end
def save_tasks
tasks.each do |task|
task.save(false)
end
end
END ^_^

No comments:
Post a Comment