Hi Jeff,
Jeff Emminger wrote:
> what you're describing is a polymorphic association.
> http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M000980
Indeed, Attachment is associated polymorphically to the other models.
What I want to accomplish is removing code duplication from some of the
controllers.
Let's say I have:
- User has_one :attachment, :as => :attachable
- Maker has_one :attachment, :as => :attachable
- Product has_many :attachments, :as => :attachable
Now, in their respective controllers, the "update" action looks like
this:
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
The "interesting" part is the one where the Attachment gets created and
associated to its "owner" (in
that case, the Product).
This part is repeated also in the UsersController and MakersController.
I thought that, trying to comply to the "everything is a resource"
mantra, I should move that part outside the afore mentioned controllers
and in a controller of its own. Say: AttachmentsController.
Routes are set as follows:
map.resources :users do |user|
user.resource :attachment, :controller => 'attachments'
end
map.resources :makers do |maker|
maker.resource :attachment, :controller => 'attachments'
end
map.resources :products do |product|
product.resources :attachments, :controller => 'attachments'
end
This leads to a problem.
User, maker and products "edit" view will have to use
AttachmentsController in order to create
a new attachment for their respective model. Hence, they will all call
AttachmentsController#create action passing parameters.
To solve this problem, I thought of implementing the "create" action
that way:
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])
And the question is:
is it correct to have AttachmentsController handle the attachments of
user, maker and product models, or should I stick with the shown
"update" action and let UsersController, MakersController and
ProductsController handle the attachments?
Now, I beg your pardon if I've been unclear (my english is worse than my
code :) ).
Thanks for your help
--
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
-~----------~----~----~----~------~----~------~--~---