Check if an instance variable has one or more objects?

痴心易碎 提交于 2019-12-25 07:28:43

问题


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


来源:https://stackoverflow.com/questions/18044895/check-if-an-instance-variable-has-one-or-more-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!