【问题标题】:Looping through array, data from multiple tables循环遍历数组,来自多个表的数据
【发布时间】:2014-08-06 11:31:21
【问题描述】:

我有一个看起来像这样的数据模型。

class Customer < ActiveRecord::Base
    has_many :trans
    has_many :sellers, through: :trans
end

class Tran < ActiveRecord::Base
    belongs_to :customers
    belongs_to :sellers
end

class Seller < ActiveRecord::Base
    has_many :trans
    has_many :customers, through: :trans
end

我正在尝试创建一个包含来自所有 3 个模型的数据的循环。这是我尝试过的:

<%= @seller.trans.sort {|a,b| b.date <=> a.date }.each do |tran| %>
  <li><%= tran %></li>
  <li><%= tran.amount %></li>
  <li><%= tran.date %></li>
<% end %>

但是,我也想包含客户的姓名(位于不同的表中)并在按日期排序的循环中链接到它。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    关联的belongs_to 部分必须是单数,然后您可以使用tran.customer 引用客户。

    class Tran < ActiveRecord::Base
      belongs_to :customer
      belongs_to :seller
    end
    

    我还建议使用order(field_name: :desc) 方法对记录进行排序,因为它会为您在数据库中进行排序。

    在下面的示例中,我假设您的Customer 模型上有一个name 属性。如果没有,则需要将其替换为要显示的链接文本。

    <%= @seller.trans.order(date: :desc) do |tran| %>
      <li><%= tran %></li>
      <li><%= tran.amount %></li>
      <li><%= tran.date %></li>
      <li><%= link_to tran.customer.name, tran.customer %></li>
    <% end %>
    

    【讨论】:

      【解决方案2】:

      首先我会解决这个问题(猜是错字)

      class Tran < ActiveRecord::Base
      
          belongs_to :customer
          belongs_to :seller
      
      end
      

      那么你应该可以输出

      <%= tran.customer.name %>
      

      【讨论】:

        猜你喜欢
        • 2011-08-28
        • 1970-01-01
        • 1970-01-01
        • 2019-07-10
        • 1970-01-01
        • 2010-10-24
        • 2022-01-27
        • 2012-08-25
        相关资源
        最近更新 更多