获取工人的每个任务的ID

时间:2012-12-24 12:56:33

标签: ruby-on-rails

这些是我的模特:

worker.rb:

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

task.rb:

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

我在:views/workers/index.html.erb列出了所有工人的名单,并在他们附近:“显示任务”。此链接将用户发送到:views/tasks/index.html.erb

tasks_controller中,我有:

def index
    @task = Worker.where(:name => params[:worker_id])
    @worker_name = params[:worker_id]
    respond_to do |format|
        format.html # show.html.erb
        format.json { render json: @worker }
    end
end

这是我的:views/tasks/index.html.erb

<center>Task of <%= @worker_name %></center><br>
<table>
   <% @task.each do |task| %>
      <tr>
        <td><%= task.name %></td>
        <td><%= task.task %></td>
        <td><%= task.done %></td>
      </tr>
    <% end %>
</table>

我想添加<td>每个任务的ID。类似的东西:

<td><%= task.id %></td>

3 个答案:

答案 0 :(得分:2)

如果我理解正确,我想你想要这样的事情:

controller.rb

@worker = Worker.find_by_name(params[:worker_id]) # might want to eager load tasks
@tasks  = @worker.tasks
# @worker_name = params[:worker_id] # don't need this anymore
...

view.html.erb

<center>Task of <%= @worker.name %></center>
<table>
  <% @tasks.each do |task| %>
  <tr>
    <td><%= task.id %></td>
    <td><%= task.name %></td>
...

答案 1 :(得分:2)

1.9.3-p194 :043 > Worker.all.each do |worker|
1.9.3-p194 :044 >   puts "workerID: "+worker.id.to_s
1.9.3-p194 :045?>   worker.tasks.each do |task|
1.9.3-p194 :046 >     puts "taskID: "+task.id.to_s
1.9.3-p194 :047?>   end
1.9.3-p194 :048?> end

控制器:添加@workers = Worker.all

查看:

<table>
   <% @workers.each do |worker| %>
      <tr>
        <td>Worker:</td>
        <td><%= worker.id %></td>
        <td><%= worker.name %></td>
        <td></td>
      </tr>
     <% worker.tasks.all
       <tr>
          <td><%= task.id %></td>
          <td><%= task.name %></td>
          <td><%= task.task %></td>
          <td><%= task.done %></td>
      </tr>
    <% end %>
</table>

答案 2 :(得分:1)

如果你想用每个任务显示id,你有很多方法,    - 你可以在迭代然后循环时将count变量打印出来    - 第二个是你可以使用ruby方法each_with_index如下;

<center>Task of <%= @worker_name %></center><br>
<table>
   <% @task.each_with_index do |task, i| %>
      <tr>
        <td><%= i %></td>
        <td><%= task.name %></td>
        <td><%= task.task %></td>
        <td><%= task.done %></td>
      </tr>
    <% end %>
</table>

我希望它会回答你的问题