0

假设我有一组@dogs,我想在一个地方渲染集合的一部分,而在另一个地方渲染其余部分。很容易将它们全部吐出:

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

但是是否可以在线操作(优化)您的集合,或者在控制器中进行这些定义并执行以下操作是更好的做法:

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

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

谢谢。

4

1 回答 1

4

集合参数只需要一个列表。没有理由这不起作用:

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

我个人更喜欢在控制器中创建这些列表。我认为看起来更好,并且可以使用命名范围变得更加干燥。

IE:

模型

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

控制器

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

看法

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

%h2 Female Dogs
= render :partial => 'dogs/summary',  :as => :dog,
  :collection => @female_dogs
于 2009-12-02T15:34:31.010 回答