Вопрос

I defined the next things:

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

I wrote the next code in "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>

in order to use the link of: new_worker_task_path,

I defined in the task_controller:

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

In addition, I defined: new.html.erb in the views/tasks, that also has: "Hi".

When I pressed the link of: "new task", I got:

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"}

first question: how can I find the worker who I want to add him a task?

second question: as I said, I defined:

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

why should I have to send the name? I use this value? I don't really understand why this parameter is necessary..

Это было полезно?

Решение

You have to send actual :param_key, which by default is ID.

So,

new_worker_task_path()

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

new_worker_task_path(@worker)

Updated for the 1st question: Let me guess what you want.

<% @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 %>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top