【问题标题】:Rails: Polymorphic Associations: How to list associationsRails:多态关联:如何列出关联
【发布时间】:2013-01-10 13:22:41
【问题描述】:

我有一个多态关联:

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>

【问题讨论】:

    标签: ruby-on-rails polymorphic-associations rails-activerecord


    【解决方案1】:

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

    def index
       @users = User.all
    end
    

    在你看来

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-24
      • 1970-01-01
      • 2019-03-14
      • 2016-04-05
      • 1970-01-01
      相关资源
      最近更新 更多