1

I'm making an ActiveRecord query that joins the contents of each of my models into an array called @contents. But I need to display the content different for data that comes from a specific model.

So in my view I need to perform some sort of test on the elements of my array:

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

How do I get the model that c comes from?

tereško
  • 58,060
  • 25
  • 98
  • 150
alt
  • 13,357
  • 19
  • 80
  • 120

2 Answers2

1

This can do the trick:

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

Going deeper: Ruby: kind_of? vs. instance_of? vs. is_a?

My short version of the comparison:

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
Community
  • 1
  • 1
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
1

You can use the is_a? method.

<% if c.is_a?(Event) %> or <% if c.is_a?(Post) %>

Simply pass the class name.

Max
  • 15,157
  • 17
  • 82
  • 127