Wrap text
Report abuse
tour.rb
class Tour < ActiveRecord::Base
has_many :customers, :through => :tour_customers
has_many :tour_customers
accepts_nested_attributes_for :customers,
:allow_destroy => false
def update_customers(customers_attributes)
new_customers = []
customers_attributes.each_pair do |key, value|
new_customers << Customer.find_or_create_by_name(value['name']) unless (!value['_delete'].blank? || !value['_destroy'].blank?)
end
self.customers = new_customers
save
end
end
tours_controller.rb
def create
customers = params[:tour][:customers_attributes]
params[:tour][:customers_attributes] = {}
@tour = Tour.new(params[:tour])
respond_to do |format|
if @tour.save && @tour.update_customers(customers)
flash[:notice] = 'Tour was successfully created.'
format.html { redirect_to(@tour) }
format.xml { render :xml => @tour, :status => :created, :location => @tour }
else
format.html { render :action => "new" }
format.xml { render :xml => @tour.errors, :status => :unprocessable_entity }
end
end
end
def update
customers = params[:tour][:customers_attributes]
params[:tour][:customers_attributes] = {}
@tour = Tour.find(params[:id])
respond_to do |format|
if @tour.update_attributes(params[:tour]) && @tour.update_customers(customers)
flash[:notice] = 'Tour was successfully updated.'
format.html { redirect_to(@tour) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @tour.errors, :status => :unprocessable_entity }
end
end
end