2

我定义了接下来的事情:

task.rb

class Task < ActiveRecord::Base
   belongs_to :worker
   attr_accessible :done, :name
end

worker.rb

class Worker < ActiveRecord::Base
  has_many :tasks
  attr_accessible :name
end

我在“views/workers/index.html.erb”中编写了下一个代码:

<h1>Listing workers</h1>

<table>
  <tr>
    <th>Name</th>
    <th>Task</th>
    <th>Done</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @workers.group_by(&:name).each do |name, tasks| %>
  <tr>
    <td><%= name %></td>
    <td><%= tasks.size %></td>
    <td><%= tasks.select{ |task| task.done != 'yes' }.size %></td>
    <td><%= link_to 'new Task', new_worker_task_path(name) %></td>
    <td><%= link_to 'Show Tasks', worker_tasks_path(name) %></td>

  </tr>
<% end %>
</table>

为了使用链接:new_worker_task_path,

我在task_controller中定义:

def new
    @worker = Worker.find(params[:worker_id])
    @task = @worker.tasks.new
    respond_with(@worker)
end

另外,我在views/tasks中定义了:new.html.erb,里面也有:“Hi”。

当我按下“新任务”的链接时,我得到了:

Couldn't find Worker with id=alon
Rails.root: /home/alon/projects/TODO

Application Trace | Framework Trace | Full Trace
app/controllers/tasks_controller.rb:48:in `new'
Request

Parameters:

{"worker_id"=>"alon"}

第一个问题:如何找到我想给他添加任务的工人?

第二个问题:正如我所说,我定义:

<td><%= link_to 'new Task', new_worker_task_path(name) %></td>

为什么我必须发送姓名?我用这个值?我真的不明白为什么这个参数是必要的..

4

1 回答 1

1

您必须发送实际的 :param_key,默认情况下是 ID。

所以,

new_worker_task_path()

# have to receive worker's ID as argument. Or worker object, accepted too...

new_worker_task_path(@worker)

更新第一个问题:让我猜你想要什么。

<% @workers.group_by(&:name).each do |name, workers| %>
  <tr>
    <td><%= name %></td>
    <td><%= workers.map {|w| w.tasks.size}.sum %></td>
    <td><%= workers.map {|w| w.tasks.select{ |task| task.done != 'yes' }.size}.sum %></td>
    <td>
      <% workers.each do |worker| %>
        <%= link_to 'new Task', new_worker_task_path(worker) %>
      <% end %>
    </td>
    <td>
      <% workers.each do |worker| %>
        <%= link_to 'Show Tasks', worker_tasks_path(worker) %>
      <% end %>
    </td>
  </tr>
<% end %>
于 2012-12-24T02:02:54.587 回答