Rails 3任务范围?

时间:2012-05-05 03:43:54

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

我正在开发一个简单的rails 3 todo应用程序,我正在尝试通过已完成的任务过滤应用程序而没有完成任务,但每当我尝试调用范围时,我都会收到错误消息。

undefined method `completed' for #<Array:0x007fe8420d0e58>

task.rb

scope :completed , where(:completed => true)
scope :incomplete , where(:finished => false)

index.html.erb

<table>
  <tr>
    <th>Name</th>
    <th>Description</th>
    <th>Finished</th>
    <th>User</th>
  </tr>
  <% @tasks.each do |task| %>
  <tr>
    <td><%= task.name %><%= button_to "complete", complete_task_path(task.id)%></td>
    <td><%= task.description %></td>
    <td><%= task.finished %></td>
    <td><%= task.user_id %></td>
    <td><%= link_to 'Show', task %></td>
    <td><%= link_to 'Edit', edit_task_path(task) %></td>
    <td><%= link_to 'Destroy', task, confirm: 'Are you sure?', method: :delete %></td>
  </tr>
<% end %>
</table>

<%= content_tag :h2, "Stuff Ive done" %>
<table>
  <tr>
    <th>Name</th>
  </tr>
  <% @tasks.completed.each do |task| %>
  <tr>
    <td><%= task.name %></td>
  </tr>
<% end %>
</table>

task_controller.rb

def complete
 @task = Task.find(params[:task_id])
 @task.completed = true
 @task.save
 redirect_to task_path
end

的routes.rb

match "tasks/:id/complete" => "task#complete", :as => :complete_task

为什么rails会给我这个错误的原因?

1 个答案:

答案 0 :(得分:0)

只需在一个地方查看您的视图(index.html.erb),就可以将其视为关系。

<% @tasks.each do |task| %>

稍后在代码中,您尝试将其作为单个对象进行访问。

<% @tasks.completed.each do |task| %>

由于您在第二个实例上看到错误,因此您需要访问“已完成”,如下所示:

<% @tasks.completed.each do |task| %>
  <% completed = task.completed %>
     <% completed.each do |com| %>

这有意义吗?