在索引表中显示关联记录 - ruby​​ on rails

时间:2017-04-21 10:46:26

标签: ruby-on-rails ruby activerecord ruby-on-rails-5 model-associations

我正在构建批发订单应用程序,我需要帮助创建一个显示多个关联记录的索引页表。

在索引表中,我想显示订单ID,客户名称(这是我正在努力的字段)和订单的总价值。

如何在索引表中显示每条记录的联系人姓名(Contact.name)?

以下是我的模型,订单控制器和订单索引视图:

订单型号

has_many :cart_contacts, dependent: :destroy
has_many :contacts, through: :cart_contacts

def customer_id
  #This is the method I’m currently trying to use to display the record 
end

def total_price
  line_items.to_a.sum { |item| item.total_price }
end

Cart_contact模型

belongs_to :cart
belongs_to :contact, optional: true
belongs_to :order, optional: true

联系模式

has_many :cart_contacts
has_many :orders, through: :cart_contacts

订单控制器

def index
  @orders = Order.all
end

订单索引视图

<table>
  <tbody>
    <% @orders.each do |order| %>
      <tr>
        <td> <%= order.id %> </td>
        <td> <%= order.customer_id %> </td>
        <td> <%= number_to_currency(order.total_price) %> </td>
      </tr>
    <% end %>
  </tbody>
</table>

任何人都可以帮我指出正确的方向吗?我觉得我可能在这里犯了一些错误。

2 个答案:

答案 0 :(得分:0)

您的Order模型应与客户建立关联 belongs_to :customer已映射到customer_id。这里有两件事:

  • 如果存在关联,那么您的方法将覆盖customer_id
  • 如果关联不存在,则需要添加(字段和关联)

在这两种情况下,您都必须删除函数customer_id

答案 1 :(得分:0)

在您的模型中,请添加以下内容

def customer_id
self.cart_contacts.joins("LEFT JOIN contacts ON contacts.id = cart_contacts.contact_id").select("contacts.name")
end

这将返回与订单关联的联系人姓名数组。希望contact_id和order_id存在于cart_contacts表中。