Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: "new or edit" path helper?

Is there a simple and straightforward way to provide a link in a view to either create a resource if it doesn't exist or edit the existing on if it does?

IE:

User has_one :profile

Currently I would be doing something like...

-if current_user.profile?
  = link_to 'Edit Profile', edit_profile_path(current_user.profile)
-else
  = link_to 'Create Profile', new_profile_path

This is ok if it's the only way, but I've been trying to see if there's a "Rails Way" to do something like:

= link_to 'Manage Profile', new_or_edit_path(current_user.profile)

Is there any nice clean way to do something like that? Something like the view equivalent of Model.find_or_create_by_attribute(....)

like image 728
Andrew Avatar asked Apr 11 '11 17:04

Andrew


1 Answers

Write a helper to encapsulate the more complex part of the logic, then your views can be clean.

# profile_helper.rb
module ProfileHelper

  def new_or_edit_profile_path(profile)
    profile ? edit_profile_path(profile) : new_profile_path(profile)
  end

end

Now in your views:

link_to 'Manage Profile', new_or_edit_profile_path(current_user.profile)
like image 113
Douglas F Shearer Avatar answered Sep 23 '22 11:09

Douglas F Shearer