views:

141

answers:

2

I have User model, where user should be able to upload one picture as an avatar. But I don't really know how to implement this in correct REST way. I see two options

First I think of avatar as of member resource that belongs to user, so I add two actions to my Users Controller, one avatar for the upload form, and second action for handling the actual upload avatar_upadte, so my routes look like

map.resources :users, :member => { :avatar => :get, :avatar_update => :post }

Second I can think of avatar as of separate resource and create Avatars Controller instead, which would be like

map.resources :users
map.resources :avatars, :only => [ :new, :create ]

I don't want to handle avatar upload in edit_user action, since it is already pretty complex.

The third option could be to have only avatar action to display the form and then user REST user update action as upload target, where form would be something like this

<% form_for @user, :url => user_path(@user), :html => { :multipart => true } do |f| %>
    <%= f.label :avatar, 'Avatar' %>
    <%= f.file_field :avatar %>
    <%= f.submit 'Upload' %>
<% end %>

But I don't like this this attitude either, because since my update action already handles another form, it would be pretty ugly to handle redirects etc.

+2  A: 

For the app I work on we do something like this:

map.resources :users do |u|
    u.resources :avatars # You can also make this a singleton resource
end

This gives you a route like: /users/1/avatars/new

This might not make sense for your app, if not I would choose the option of having a separate AvatarsController.

jonnii
+1  A: 

If I understand correctly:

  • Option 1 adds a custom action to the User resource, which is best avoided if at all possible.
  • Option 2 splits User and Avatar into separate resources, but doesn't make it easy to connect the two (for example, when creating an upload form).
  • Option 3 looks like you'd view the Avatar as a User attribute.

The most important thing to figure out at this point is: what's the cardinality of the relationship between User and Avatar. Does a User have one Avatar or many? If there's a one-to-many relationship, then a solution like the one Jonnii proposes might make sense.

If a User will only have one Avatar (which seems likely), I would consider going with the simplest solution and make the Avatar a User attribute.

Although I haven't gotten around to trying it out, I've heard good things about Paperclip. The example usages even discuss using Paperclip with avatars.

For an even more lightweight solution, you might consider Gravatar, which would eliminate the need for a file upload entirely and simplify things a lot.

Rich Apodaca
actualy, I'm using paperclip, so avatar works as an attribute of User model, but since it is already quite complex, I don't want to put it to the same edit action.
Darth