Sangwoo Park
Sangwoo Park

Reputation: 125

How can I get the model name of object in rails?

I got four different models.

Here's an example,

@single = Single.all
@coe = Coe.all
@blend = Blend.all
@production = @single+@coe+@blend

then how to check which model @production is?

I tried

<% @production.each do |p| %>
  <%=p.class.name%>
<% end %>

but it returns "Array"

It seems to be simple, but I can't find out (I edited question)

Upvotes: 5

Views: 18453

Answers (3)

Asnad Atta
Asnad Atta

Reputation: 4003

The problem is here

@single = Single.all
@coe = Coe.all
@blend = Blend.all
@production = @single+@coe+@blend

change these lines with

@single = Single.all.to_a
@coe = Coe.all.to_a
@blend = Blend.all.to_a
@production = @single+@coe+@blend

and then if you will check

@production.first.class.name #Single
@production.last.class.name #Blend

so in your view you can do this

<% @production.each do |p| %>
  <% p.each do |product| %>
    <%= product.class.name %>
  <% end %>
<% end %>

Upvotes: 13

power
power

Reputation: 1265

if while iterating on @production it returns array so you need to try this.

<% @production.each do |p| %>
  <% p.each do |product| %>
    <%= product.class.name %>
  <% end %>
<% end %>

Upvotes: 2

mrvncaragay
mrvncaragay

Reputation: 1260

@production is a collections of combinations of single, coe, and blend thats why @production.class.name doesnt work, you need to iterate each object like this:

<% @production.each do |object| %>
  <%= object.class.name %>
<% end %>

Upvotes: 1

Related Questions