render :partial with a manipulated :collection
-
11-09-2019 - |
Question
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.
Solution
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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow