0

这是一个原始的待办事项列表应用程序,其中包含属于项目的任务。在视图中,我在相关项目下方显示任务,其中包含用于编辑和删除每个项目的链接。

<% @projects.each do |project| %>

<h2><%= project.name %></h2>
<%= link_to 'Edit', edit_project_path(project) %>
<%= link_to 'Destroy', project_path(project), 
   method: :delete, data: { confirm: 'Are you sure?' } %>
<%= form_for([project, project.tasks.new]) do |f| %>
<%= f.label :name %><br />
<%= f.text_field :name %>
<%= f.submit %>
<% end %>
<% project.tasks.each do |task| %>
<%= task.name %>
<%= link_to 'Destroy Task', [task.project, task],
           method: :delete,
           data: { confirm: 'Are you sure?' } %>
<%= link_to 'Edit Task', edit_project_task_path(task.project, task) %>
<% end %>
<% end %>

<%= link_to 'New TODO list', new_project_path %>

但是,在呈现的页面中,Edit 和 Destroy 链接比预期的多 2 个。链接指向 ../projects/id/tasks/ 和 ../projects/id/tasks//edit

这是任务模型

class Task < ActiveRecord::Base
  belongs_to :project
end

这是任务控制器

class TasksController < ApplicationController
  def create
    @project = Project.find(params[:project_id])
    @task = @project.tasks.create(params[:task].permit(:name, :completed))
    redirect_to projects_path
  end
  def destroy
    @project = Project.find(params[:project_id])
    @task = @project.tasks.find(params[:id])
    @task.destroy
    redirect_to projects_path
  end
  def edit
    @project = Project.find(params[:project_id])
    @task = @project.tasks.find(params[:id])
  end
  def update
    @project = Project.find(params[:project_id])
    @task = @project.tasks.find(params[:id]) 
    redirect_to projects_path
  end
end

再次感谢你的帮助!

4

1 回答 1

0

这是预期的行为,因为您将链接放在 2 个循环中,一个 for@projects另一个 for @tasks。这就是为什么它正在发生。你应该做这个:

<% @tasks = @projects.map{|x| x.tasks} %>    
<% @tasks.each do |task| %>
  <%= task.project.name %>
  <ul>    
    <li><%= task.name %>
      <%= link_to 'Destroy Task', project_task_path(task.project, task),
           method: :delete,
           data: { confirm: 'Are you sure?' } %>
      <%= link_to 'Edit Task', edit_project_task_path(task.project, task) %>
    </li>
  </ul>
<% end %>

谢谢

我也在重构你的任务代码,

class TasksController < ApplicationController

  before_action :load_task, except: :create

  def create
    @project = Project.find(params[:project_id])
    @task = @project.tasks.create(params[:task].permit(:name, :completed))
    redirect_to projects_path
  end

  def destroy       
    @task.destroy
    redirect_to projects_path
  end

  def edit       
  end

  def update        
    redirect_to projects_path
  end

 private
  def load_task
    @project = Project.find(params[:project_id])
    @task = @project.tasks.find(params[:id]) 
  end
end
于 2013-08-08T17:20:16.330 回答