简体   繁体   English

Ruby on Rails外键

[英]ruby on rails foreign keys

basically what I am trying to do is use a foreign key. 基本上我想做的是使用外键。 Eg 144 which will return an object. 例如144,它将返回一个对象。 I keep getting an error saying the record number cannot be found. 我总是收到一条错误消息,说找不到记录号。

In the order show view. 在订单显示视图中。

(I have tested it and @order.cart_id is valid and does return a number. Eg 144 (我已经对其进行了测试,并且@ order.cart_id有效,并且确实返回了数字。例如144

<b>Order items:</b>
<%= @cart.get_order_cart(@order.cart_id) %>

In cart model, get_order_cart method 在购物车模型中,使用get_order_cart方法

def get_order_cart(cart_id)
  cart = Cart.find(cart_id)
  cart.line_items.each do |item| 
    item.product.title
  end
end

Like I say though, this doesn't work. 就像我说的那样,这是行不通的。 What is the problem please? 请问是什么问题? Thanks 谢谢

Why don't you use ActiveRecord associations? 为什么不使用ActiveRecord关联?

class Order < ActiveRecord::Base
  belongs_to :cart
end

class Cart < ActiveRecord::Base
  has_many :orders
end

Now, you can get your cart simply by 现在,您可以通过

@cart = @order.cart

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM