我有一个多态关联:
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>