【发布时间】:2017-04-21 10:46:25
【问题描述】:
我正在构建一个批发订单应用程序,我需要帮助创建一个显示多个关联记录的索引页表。
在索引表中,我想显示订单 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>
谁能帮我指出正确的方向?我觉得我可能在这里做错了几件事。
【问题讨论】:
-
客户是您数据库中的表吗?
-
客户和订单表是如何关联的?您是否将联系人作为客户提及?
-
是的,所以 Customer 是一个联系人并且 Contact has_many Cart_Contacts 并且关联是 Orders has_many :contacts, through: :cart_contacts。
标签: ruby-on-rails ruby activerecord ruby-on-rails-5 model-associations