我有User
,List
和Task
型号。
任务 belongs_to
用户和列表,列表 has_many
< em>任务和belongs_to
用户,以及用户 has_many
列表和{{1} } 任务。
我有一部分想要在我的索引视图中显示的内容,只有一个我想要挂起的snafu。
我能够在所有列表的索引视图中显示第一个创建的任务。问题是,即使列表未与任务相关联,也会为所有列表显示创建的第一个任务。
在列表索引视图中,我希望创建的第一个任务仅在与列表关联时显示。
任务模型:
has_many
列出索引视图 -
class Task < ActiveRecord::Base
attr_accessible :completed, :description, :list_id, :user_id
belongs_to :list
belongs_to :user
scope :completed, where(:completed => true)
scope :incomplete, where(:completed => false)
def self.most_recent
first(:order => 'id ASC' ) # or whatever query you need to get the most recent
end
end
我还是铁杆新手,但我知道我非常接近。我在这里俯瞰什么? 强调文字
===========
我已经测试了@ Baldrick的解决方案,现在似乎又出现了另一个错误
我对所述解决方案的看法 -
<div class="span12 offset2">
<% @lists.each do |list| %>
<div class="well row span4">
<div class="span3">
</div>
<div class="span4">
<span class="lead">
<%= link_to "#{list.name}", list_url(list) %>
</span>
<p>
<%= list.description %>
</p><hr>
<div class="pull-right" id="gage-<%= list.id %>" style="width:170px; height:100px;"></div>
<br>
<span class="offset1">
<% if Task.most_recent %>
<span class="pull-left"> <%= image_tag Task.most_recent.user.gravatar_url, :class => "gravatar_index" %></span>
<% end %>
</span>
</div>
<% end %>
</div>
我现在收到错误 -
<% if Task.most_recent(list) %>
<span class="pull-left"> <%= image_tag Task.most_recent.user.gravatar_url, :class => "gravatar_index" %></span>
<% end %>
我不能正确理解,因为我在创建任务模型时有这样一个创建的列
SQLite3::SQLException: no such column: tasks.list: SELECT "tasks".* FROM "tasks" WHERE "tasks"."list" = 4 ORDER BY id ASC LIMIT 1
这是我需要添加索引才能进行查询的情况吗?
答案 0 :(得分:2)
方法most_recent
为您提供所有任务的最后一个创建任务。你知道什么是给定列表的最新任务。
您应该为列表提供参数
def self.most_recent(list)
where(list_id: list.id).order('id ASC').first # or whatever query you need to get the most recent
end
答案 1 :(得分:1)
您的most_recent
方法返回任务的第一项任务。此方法中没有任何内容将任务绑定到任何列表。您需要将list_id传递给此方法以获取此列表的第一个任务,例如
def self.most_recent(list_id)
first(:order => 'id ASC', :list_id => list_id)
end
编辑:其他解决方案无效。
答案 2 :(得分:0)
根据您的描述,对于每个列表,不声音可以为您显示该列表的最新任务。相反,您似乎希望将整体最近的任务多次出现,对于恰好包含它的每个列表一次。要实现此目的,您需要将if Task.most_recent
替换为if list.tasks.include? Task.most_recent
。
--- --- EDIT
好的,如果你真的想要为每个列表显示该列表的最近的任务,那么你应该以相同的方式进行此操作。在List
课程中,您应该使用以下方法:
def most_recent_task
tasks.first(:order => 'id ASC') # or whatever
end
然后在您的视图中,您将Task.most_recent
的两个匹配项替换为list.most_recent_task
。如果你的列表总是至少有一个任务,那么你可以完全摆脱保护条款(即if
)。
作为进一步的重构,您可能希望从视图中进行一些计算,并为列表索引创建“演示者”,这只是每个列表的演示者数组。单个演示者应该是一个普通对象,其中包含有关列表的所需信息,预先计算: