Joseph Tura
Joseph Tura

Reputation: 6360

Rails: Polymorphic Associations: How to list associations

I have a polymorphic assocation:

class User < ActiveRecord::Base
  belongs_to :companiable, :polymorphic => true
end

class Agency < ActiveRecord::Base
  has_many :users, :as => :companiable
end

class Publisher < ActiveRecord::Base
  has_many :users, :as => :companiable
end

and now I want to list all users and show the company they belong to. Is there a more elegant solution than this (strongly hope there is)?

def index
    @publishers = Publisher.all
    @agencies = Agency.all
    @users = User.all
end

...

<td><% unless user.companiable_id.nil? %>
            <% if user.companiable_type == "Agency" %>
              <%= @agencies[user.companiable_id].name %>
            <% elsif user.companiable_type == "Publisher"%>
              <%= @publishers[user.companiable_id].name %>
            <% end %>
          <% end %>
        </td>

Upvotes: 0

Views: 257

Answers (1)

John Furtado
John Furtado

Reputation: 555

You can acces the company from user, since the belongs_to adds a method so that you can access the other object directly by doing user.companiable

def index
   @users = User.all
end

and in your view

<td><% unless user.companiable.nil? %>
       <%= user.companiable.name %>
    <% end %></td>

Upvotes: 2

Related Questions