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
  • 57,247
  • 24
  • 95
  • 149
alt
  • 12,593
  • 18
  • 75
  • 118

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
  • 52,976
  • 12
  • 120
  • 112
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
  • 14,085
  • 14
  • 75
  • 120