0

我有一个多态关联:

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

现在我想列出所有用户并显示他们所属的公司。有没有比这更优雅的解决方案(强烈希望有)?

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>
4

1 回答 1

2

您可以从用户访问公司,因为belongs_to添加了一个方法,以便您可以通过执行直接访问其他对象user.companiable

def index
   @users = User.all
end

在你看来

<td><% unless user.companiable.nil? %>
       <%= user.companiable.name %>
    <% end %></td>
于 2013-01-10T13:29:49.663 回答