First off, I beg your pardon for the somewhat cryptic topic, but I
couln't think of anything better.

The issue I'm facing is that I have some models (User, Product, Maker)
which can have one or more
attachments:

A User has_one avatar
A Maker has_one logo
A Product has_many pictures, and has_many documents

"Avatar", "logo" and "documents" are all aliases for a model named
"Attachment" and, thus, the
aforementioned relations are all polymorphic.

I'm using "attachment_fu" plugin to handle attachments.

While writing the code I've found that there are many such constructs
repeating all over:

  def update
    flash[:error] = "couldn't update product" unless
@product.update_attributes(params[:product])
    if !params[:attachment].blank?
      flash[:error] = "couldn't add the attachment" unless
@product.attachments << Attachment.create(params[:attachment])
    end
    redirect_to edit_product_path(@product)
  end

This smells a lot. I thought there should be one controller in charge of
handling attachments, namely
AttachmentsController, so far so good.

But...since the AttachmentsController would be "REST style", it will
only have one "create" action which
will be used in different contexts (User, Product, Maker).
Create action will be passed the usual "params" hash built like this:
:xxxxx_id => 1, :uploaded_data => "...."

Where "xxxxx_id" will be replaced by "user_id", "product_id" and
"maker_id" depending on the what
model I'm creating attachment for.

Being params: :user_id => 1, :uploaded_data => "some stuff"

I thought the AttachmentsController#create action should look like:

context = params.keys.find do |k| k.to_s =~ /.*_id/ end
class_type = eval(context.to_s.gsub(/.*_id/,'').classify)
instance = class_type.find(params[context])
instance.attachments.create(params[:uploaded_data])

Is that a correct way to proceed, or there's an easier and cleaner way?

Thanks in advance for your help

Regards,
Carmine
-- 
Posted via http://www.ruby-forum.com/.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to