Rails:“新建或编辑”路径助手?
是否有一种简单直接的方法可以在视图中提供链接,以便在资源不存在时创建资源,或者在资源存在时编辑现有资源?
IE:
User has_one :profile
目前我会做类似的事情......
-if current_user.profile?
= link_to 'Edit Profile', edit_profile_path(current_user.profile)
-else
= link_to 'Create Profile', new_profile_path
如果这是唯一的方法,那没关系,但我一直在尝试看看是否有“Rails Way”来做类似的事情:
= link_to 'Manage Profile', new_or_edit_path(current_user.profile)
是否有任何好的干净的方法来做某事就这样?类似于 Model.find_or_create_by_attribute(....)
的视图
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(....)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
编写一个助手来封装逻辑中更复杂的部分,然后你的视图就可以干净了。
现在您的看法是:
Write a helper to encapsulate the more complex part of the logic, then your views can be clean.
Now in your views:
我遇到了同样的问题,但我想为很多模型做这件事。为每个模型编写一个新的助手似乎很乏味,所以我想出了这个:
然后你可以为父模型的任何子模型调用
new_or_edit_path :child
。I came across this same problem, but had a lot of models I wanted to do it for. It seemed tedious to have to write a new helper for each one so I came up with this:
Then you can just call
new_or_edit_path :child
for any child of the parent model.另一种方式!
Another way!
如果您想要一种通用方法:
其中
model
是视图上的实例变量。例子:If you want a generic way:
Where
model
is your instance variable on your view. Example:试试这个:
并使用您的链接:
Try this:
and with your link like: