检查实例变量是否具有一个或多个对象? [英] Check if an instance variable has one or more objects?

查看:101
本文介绍了检查实例变量是否具有一个或多个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个示例代码,仅用于说明问题.

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

单击其中一个按钮时,我会将一些实例变量加载到视图中并进行渲染.我不知道该变量是否在内部具有一个或多个对象.因此,在将变量加载到视图中时,我必须检查该变量内部是否具有一个或多个对象(否则,如果内部仅存在一个对象,则.each方法将失败).还是有一种方法可以将变量内的一个对象仅存储为数组?

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

推荐答案

如果您要检索的@animals不是如下所示的数组,则可以将@animals作为数组返回:

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

这篇关于检查实例变量是否具有一个或多个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆