I have a User, List, and Task models.
A task belongs_to user and list, a list has_many tasks and belongs_to user, and a user has_many list and has_many tasks.
I have part of what I want to display working in my index view, with just one snafu that I am getting hung up on.
I’m able to display the first created task in the index view of all the lists. The problem is, the first task created is displayed for all of the lists, even if the list is NOT associated with the task.
In the list index view I want the first task created to display only if it is associated with the list.
Task model:
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
List Index View-
<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>
I’m still new to rails but I know I’m very close. What am I overlooking here? emphasized text
===========
EDIT
I’ve tested @Baldrick’s solution and now seem to be getting another error
My view with described solution-
<% if Task.most_recent(list) %>
<span class="pull-left"> <%= image_tag Task.most_recent.user.gravatar_url, :class => "gravatar_index" %></span>
<% end %>
I am now getting the error-
SQLite3::SQLException: no such column: tasks.list: SELECT "tasks".* FROM "tasks" WHERE "tasks"."list" = 4 ORDER BY id ASC LIMIT 1
I must not be understanding correctly because I have such a created column when I created the Task model
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
Is this a case where I need to add an index to be able to make my query?
The method
most_recentgives you the last create task of all tasks. What you wnat is the most recent task of a given list.You should give a parameter to the list