Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 728
Sangwoo Park Avatar asked Jul 20 '16 05:07

Sangwoo Park


2 Answers

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 %>
like image 122
Asnad Atta Avatar answered Oct 06 '22 00:10

Asnad Atta


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 %>
like image 45
power Avatar answered Oct 06 '22 01:10

power