Rails 3:孤立视图中的“编辑”和“删除”链接

时间:2013-08-08 16:45:06

标签: ruby-on-rails ruby-on-rails-3

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

<% @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 %>

但是,在渲染页面中,还有2个比预期更多的编辑和销毁链接。 链接指向../projects/id/tasks/和../ projects / id / tasks //编辑

这是任务模型

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

再次感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这是预期的行为,因为您将链接放在2个循环中,一个用于@projects,另一个用于@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