Rubytastic
Rubytastic

Reputation: 15491

best way to rewrite /profiles/1/edit/details towards /me/profile/details?

Im trying to namespace several routes under a "me" /me section to have all user profile/account based stuff under this namespace for more clean routing.

What would be the best way to approach this? I find that rewriting the default REST routing ( profiles/1/edit ) gives several issues like forms not updating.

Routes

get "/me/profile"              => "profiles#show", :as => :my_profile
get "/me/profile/:what"        => "profiles#edit", :as => :my_profile_edit
post "/me/profile/:what"       => "profiles#edit"

ProfilesController

def edit
  @profile      = current_user.profile
  if ["basics", "location", "details", "photos"].member?(params[:what])
    render :action => "edit/edit_#{params[:what]}"
  else
    render :action => "edit/edit_basics"
  end
end

def update
  @profile        = current_user.profile
  @profile.form   = params[:form]
  respond_to do |format|
    if @profile.update_attributes!(params[:profile])
      format.html { redirect_to :back, :notice => t('notice.saved') }
    else
      format.html { render action => "/me/profile/" + @profile.form }
    end
  end
end

If feels like above is going very bad against the REST principle. How could I achieve the wanted results in a better way?

Upvotes: 0

Views: 62

Answers (1)

Almaron
Almaron

Reputation: 4147

Well, if you really want to stick to the REST that much, I'd recomend moving the :what into the GET params hash. Then you can rewrite your routes like this

scope "/me" do
  resource :profile, :only => [:show, :edit, :update]

So than you'll be adressing the edit page as profile_edit_path(:what => "details")

Couple more things about your code.

  • you should change update_attributes to update
  • you should not use the redirect :back, 'cause it's gonna render a js back link and not do the actual request, so you wouldn't see the actual changes
  • you should change render action => to render :template =>
  • you should not use params[:profile] in your update statemen unless you are using strong_params. You need to specify, what params to permit from the form. It's done for protection from mass-assignment.

Think you should really check out the CodeSchool tutorial on Rails 4.

Upvotes: 1

Related Questions