【问题标题】:Showing associated records in a index table - ruby on rails在索引表中显示关联记录 - ruby​​ on rails
【发布时间】: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


【解决方案1】:

您的Order 模型应该通过以下方式与客户建立关联 belongs_to :customer 已映射到 customer_id。所以这里有两件事:

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

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

【讨论】:

    【解决方案2】:

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

    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 表中。

    【讨论】:

    • 谢谢!我认为这是正确的,但是这是返回的内容:“#<:activerecord_associationrelation:0x007fc8e03aa8f8>”而不是名称。我怎样才能让它返回“名称”?
    • cart_contacts 表中的属性是什么?
    • cart_contact 表中的属性有:contact_id, order_id & cart_id。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多