如何在同一个地方渲染不同的集合?

How to render different collections at the same place?

假设,我有一个名为 Animal 的模型。此模型包含具有两种可能状态的枚举属性 kind

class Animal < ActiveRecord::Base
  enum kind: [ :cat, :dog ]
end

然后在我的控制器中创建相应的实例变量集合。

class AnimalsController < ApplicationController
  def index
    @cats = Animal.cat
    @dogs = Animal.dog
  end
end

在我看来,我有两个 link 和两个集合。

<h1>Animals</h1>

<b><%= link_to 'List Cats' %></b>
<b><%= link_to 'List Dogs' %></b>

<%= render partial: 'animals/cat', collection: @cats, as: :cat %>
<%= render partial: 'animals/dog', collection: @dogs, as: :dog %>

在同一位置显示第一个集合而不是第二个集合或第二个集合而不是第一个集合的首选方式是什么,具体取决于点击 link?怎么做?

您可以编写以下代码在不同列表之间切换

<%= link_to "List Cats", animals_path(:cat => true) if params[:dog] %>
<%= link_to "List Dogs", animals_path(:dog => true) if params[:cat] %>

<div id="list">
 <% if params[:cat] == true %>
  <%= render partial: 'animals/cat', collection: @cats, as: :cat  %>
 <% elsif params[:dog] == true  %>
  <%= render partial: 'animals/dog', collection: @dogs, as: :dog  %>
 <% end %>
</div>