【发布时间】:2012-10-28 08:43:50
【问题描述】:
我有 User、List 和 Task 模型。
一个任务belongs_to用户和列表,一个列表has_many任务 和 belongs_to user,以及 user has_many list 和 has_many tasks。
我想要在我的索引视图中显示的部分内容正在工作,只有一个让我挂断的问题。
我能够在所有列表的索引视图中显示第一个创建的任务。问题是,为所有列表显示创建的第一个任务,即使列表与任务无关。
在列表索引视图中,我希望创建的第一个任务仅在与列表关联时才显示。
任务模型:
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
列表索引视图-
<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>
我对 Rails 还是很陌生,但我知道我已经很接近了。我在这里俯瞰什么? 强调文字
============
编辑
我已经测试了@Baldrick 的解决方案,现在似乎又遇到了另一个错误
我对所描述解决方案的看法-
<% 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
我一定没有正确理解,因为我在创建任务模型时创建了这样一个列
class CreateTasks < ActiveRecord::Migration
def change
create_table :tasks do |t|
t.string :description
t.boolean :completed, :default => false
t.integer :list_id
t.timestamps
end
end
end
这是我需要添加索引才能进行查询的情况吗?
【问题讨论】:
-
每个块缺少的
<% end %>只是一个错字吗? -
没错,它在 c 和 p 上被忽略了。
-
抱怨是因为使用了列表而不是 list_id。这是因为@Baldrick 的代码中有错误。在 most_recent 方法中,该方法应该与我在答案中作为第一选择的方法一样。使用 Baldrick 的代码,应该是
where(list_id: list).order('id ASC').first
标签: ruby-on-rails activerecord view model