have an organisation class, and organisations can be clients, suppliers, printers or prospects.
Want to be able to control this through a form - using check boxes.
The models etc are:
class Client <>
belongs_to :organisation
class Printer <>
belongs_to :organisation
class Organisation <>
has_one :printer
has_one :client
But have had a nightmare sorting out the controller for handling all of this. I am sure there is a better way of doing this.
def update
#get the org type ids
params[:organisation_type_ids] ||= []
#check to se if we have clients etc for those org types
debugger
client = Client.find_by_organisation_id(@organisation.id)
printer = Printer.find_by_organisation_id(@organisation.id)
if params[:organisation_type_ids].length > 0
params[:organisation_type_ids].each do |ot|
case ot.to_i
when 1:
if client.nil?
@organisation.create_client()
end
when 2:
if printer.nil?
@organisation.create_printer()
end
else
end
end
else #none are checked - so get rid of any that exist
if client
@organisation.client.destroy
end
if printer
@organisation.printer.destroy
end
end
#now get rid of any that have been unchecked
#ie client/printer exist but are not in params[:organisation_type_ids]
unless client.nil?
unless params[:organisation_type_ids].include?('1')
@organisation.client.destroy
end
end
unless printer.nil?
unless params[:organisation_type_ids].include?('2')
@organisation.printer.destroy
end
end
It seems the very opposite of DRY (is that wet?) and very, very kludgy. Sure it works, but I am sure that I am failing to understand the power of associations to do the heavy lifting for me.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment