link_to创建新的nested_resource

时间:2012-12-24 01:45:39

标签: ruby-on-rails nested-resources

我定义了接下来的事情:

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

另外,我定义了:view / tasks中的new.html.erb,它还有:“你好”。

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

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>

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

1 个答案:

答案 0 :(得分: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 %>
相关问题