简体   繁体   English

Rails-链接到新动作,而不是显示不存在的项目?

[英]Rails - link to new action instead of show if an item doesn't exist?

I'm trying to create a link so that if the current user has a project already created, then they just click the 'Project' link, and it will take them to their project. 我正在尝试创建一个链接,以便如果当前用户已经创建了一个项目,那么他们只需单击“项目”链接,它将把他们带到他们的项目。 Each user can only have one project. 每个用户只能有一个项目。 If they don't have a project, then it will instead take them to the form to create one (ie the new view/action). 如果他们没有项目,那么它将带他们到表单中以创建一个项目(即新的视图/动作)。

How would I go about this? 我将如何处理? I apologise, I'm new to rails. 抱歉,我是新手。 At the moment, I am using the following: 目前,我正在使用以下内容:

<%= link_to 'Project', project_path %>

which works fine if the user already has a project, but says "No route matches {:action=>"show", :controller=>"projects"}" if one doesn't exist. 如果用户已经有一个项目,则可以正常工作,但是如果不存在,则说“ No route match {:action =>“ show”,:controller =>“ projects”}“”。 I'm not sure where to start - do I add in conditions to the link_to, or is it something I need to put in the controller? 我不确定从哪里开始-是否要在link_to中添加条件,还是我需要在控制器中放入某些内容? Thanks! 谢谢!

I guess you should check it inside the new action. 我想您应该在new操作中检查它。 Find project if exist and redirect to the edit action. 查找项目(如果存在)并重定向到edit操作。

If you will decide which link to render user can cheat you and type /projects/new in address bar. 如果您决定要渲染的链接用户可以欺骗您,请在地址栏中键入/projects/new

<%= link_to 'Project', 
      current_user.project.present? ? 
        project_path(current_user.project) : 
        new_project_path %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM