t56k
t56k

Reputation: 6981

Rails: multiple-class methods

I'm presenting users a list of assets they've created. They can be different classes, and each has an edit button.

What'd be the best way to write a method that takes the user to the correct edit form depending on what the class is?

Something like this is what I'm thinking:

def edit_asset(class, id)
  if class == 'Photo'
    redirect_to edit_photo_url(id)
  elsif class == 'Audio'
    redirect_to edit_audio_url(id)
  elsif ...
    ...
  end
end

Is there a better way to do this? Any where should this method go? Thanks!

EDIT

I forgot to mention that the classes could either be classes or subclasses.

Upvotes: 0

Views: 138

Answers (3)

Zippie
Zippie

Reputation: 6088

You could do:

def edit_asset(class, id)
    redirect_to send("edit_#{class.lowercase}_url", id) 
end

Upvotes: 0

Bigxiang
Bigxiang

Reputation: 6692

How about use polymorphic_url in rails? You can search the api for it.

redirect_to polymorphic_url(yourclassname.constantize.find(yourid), action: 'edit')

Upvotes: 1

bgates
bgates

Reputation: 2373

You can actually just do link_to 'Edit', [:edit, @object], assuming @object is listed as a resource in your routes file.

Upvotes: 2

Related Questions