class Article
has_many :completed_stories, :conditions => [ ‘complete = ?’, true ]
end
(If you’re declaring the complete column to be a boolean, then this
is better than using 1 even though the SQL will be exactly the same
as it reveals the meaning more.)
in view:
for story in @article.completed_stories
Alternatively, you could set a @completed_stories instance variable
in the controller and just have “for story in @completed_stories” in
the view.
You’ll find that the system is more easily changed later if you push
this kind of logic into the model wherever practical.
class Article
has_many :completed_stories, :conditions => [ ‘complete = ?’, true ]
end
Ah - that’s great thanks. I ended up doing something similar, making a
method in the article model:
def completed_stories
Story.find(:all, :conditions => [“article_id = ? and complete = ?”,
self, 1])
end
but your suggested way is much nicer. Cheers!
Actually there’s an amendment needed (in my case at least), in case
anyone else is trying to do this: you need to specify the class that
:completed_stories is coming from:
There are a couple ways to do it that I would suggest.
Adding another association works but it’s a bit cumbersome. Luckily,
rails provides these lovely association extensions you can use to
define new methods on the association:
class Article < ActiveRecord::Base
has_many :stories do
def completed
find(:all, :conditions => “complete = 1”)
end
end
This allows you to do:
@article.stories.completed
rather than @article.completed_stories
Alternatively, once you’re in the view, you can always use select to
filter the array:
@article.stories.select{ |story| story.complete == 1}.each do |
story| ;; end
Not the cleanest, but if you’re already using @article.stories
elsewhere, it won’t hit the database again.