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(....)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With