【问题标题】:Get the model an Active Record object is in获取 Active Record 对象所在的模型
【发布时间】:2013-01-28 05:06:21
【问题描述】:

我正在创建一个 ActiveRecord 查询,它将我的每个模型的内容连接到一个名为 @contents 的数组中。但是对于来自特定模型的数据,我需要显示不同的内容。

所以在我看来,我需要对数组的元素进行某种测试:

<% @contents.each do |c| %>
  <article>
    <% if [TEST FOR EVENT] %>
      EVENT HTML
    <% elsif [TEST FOR POST] %>
      POST HTML
    <% end %>
  </article>
<% end %>

如何获取c来自的模型?

【问题讨论】:

    标签: ruby-on-rails ruby rails-activerecord


    【解决方案1】:

    这可以解决问题:

    c.kind_of?(Event) #=> true or false
    

    更深入:Ruby: kind_of? vs. instance_of? vs. is_a?

    我的比较的简短版本:

    3.class #=> Fixnum
    3.is_a? Integer #=> true
    3.kind_of? Integer #=> true
    3.instance_of? Integer #=> false
    # is_a? & kind_of? can 'detect' subclasses, when instance_of? does not
    

    【讨论】:

    • 将在 4 分钟内接受。感谢您参考 kind_of 和 is_a 和 instance_of 的区别。
    • 还有case c when Event then ...
    【解决方案2】:

    您可以使用is_a? 方法。

    &lt;% if c.is_a?(Event) %&gt;&lt;% if c.is_a?(Post) %&gt;

    只需传递类名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      相关资源
      最近更新 更多