views:

208

answers:

1

Hi.

Say I have a collection of @dogs, and I want to render part of the collection in one place and the rest in another. It's easy to spit them all out together:

render :partial => 'dogs/summary', :collection => @dogs, :as => :dog

But is it possible to manipulate (refine) your collection in-line, or is it better practice to make those definitions in your controller and do something like:

%h2 Male Dogs:
render :partial => 'dogs/summary', :collection => @male_dogs, :as => :dog

%h2 Female Dogs:
render :partial => 'dogs/summary', :collection => @female_dogs, :as => :dog

Thanks.

A: 

The collection argument just takes a list. There's no reason why this wouldn't work:

render :partial => 'dogs/summary',  :as => :dog,
  :collection => @dogs.select{|dog| dog.gender == "M"}

Personally I prefer creating those lists in the controller. I think looks better, and can be made much more DRY with named scopes.

IE:

Model

class dog < ActiveRecord::Base
   named_scope :male, :conditions => {:gender => "M"}
   named_scope :female, :conditions => {:gender => "F"}
   ...
end

Controller

class DogsController < ApplicationController
  ...
  def index
    if params[:user_id]
      @user = User.find(params[:user_id])
      @male_dogs = @user.dogs.male
      @female_dogs = @user.dogs.female
    else
      @male_dogs = Dog.male
      @female_dogs = Dog.female
    end
  end
end

View

%h2 Male Dogs
= render :partial => 'dogs/summary',  :as => :dog,
  :collection => @male_dogs

%h2 Female Dogs
= render :partial => 'dogs/summary',  :as => :dog,
  :collection => @female_dogs
EmFi
That's perfect. Thanks so much!
doctororange
Simone Carletti
@weppos: That is a good addition for recent ruby implementations. It also works for the case where named\_scopes won't do.
EmFi