-->

Check if an instance variable has one or more obje

2019-08-17 00:56发布

问题:

This is an example code, just to illustrate the problem.

When I click one of the buttons I will load some instance variable into the view and render it. I don't know if the variable will have one or more objects inside. I therefore have to check if the variable has one or more objects inside, when it is loaded into the view (else the .each method will fail if there is only one object inside). Or is there a way to store just one object inside the variable as an array?

aa.html.erb

<div class="fill"></div>
<%= button_to 'ALL', { :controller => 'animals', :action => 'vaa', :id => "0" } , remote: true %>
<%= button_to 'ELEPHANT', { :controller => 'animals', :action => 'vaa', :id => "1" } , remote: true %>
<%= button_to 'ZEBRA', { :controller => 'animals', :action => 'vaa', :id => "2" } , remote: true %>

<div class="fill3"></div>


<%= render 'animals/vaa' %>

_vaa.html.erb

<div class="fill4">
    <% @animals.each do |animal| %>
    <table>
        <tr>
            <td><%= animal.name %></td>
            <td><%= animal.race %></td>
            <td><%= link_to 'Show', animal %></td>
            <td><%= link_to 'Edit', edit_animal_path(animal) %></td>
            <td><%= link_to 'Destroy', animal, method: :delete, data: { confirm: 'Are you sure?' } %></td>
        </tr>
    </table>
    <% end %>
</div>
<div class="fill5">
</div>

animals_controller.rb

def vaa
    if params[:id] == "0"
      @animals = Animal.all
    elsif params[:id] == "1"
      @animals = Animal.first
    elsif params[:id] == "2"
      @animals.second
    end
    respond_to do |format|
      format.js
    end
  end

回答1:

You can return @animals as array if @animals you're retrieving is not an array like follows:

  def vaa
    if params[:id] == "0"
      @animals = Animal.all
    elsif params[:id] == "1"
      @animals = Animal.first
    elsif params[:id] == "2"
      @animals.second
    end

    # The following line makes sure @animals is Array if @animals is not an array.
    @animals = [@animals] unless @animals.kind_of?(Array) 

    respond_to do |format|
      format.js
    end
  end