循环遍历数组,来自多个表的数据

时间:2014-08-06 11:31:21

标签: ruby-on-rails ruby activerecord

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

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

但是,我想要包含Customer的名称(在不同的表中)并在按日期排序的循环中链接到它。

2 个答案:

答案 0 :(得分:0)

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

class Tran < ActiveRecord::Base

    belongs_to :customer
    belongs_to :seller

end

然后你应该能够输出

<%= tran.customer.name %>

答案 1 :(得分:0)

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

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

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

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

<%= @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 %>
相关问题