Rails无法从关联中获得价值

时间:2018-08-21 05:09:09

标签: ruby-on-rails

我在架构中有2个表,分别为:(base) C:\Users\ADMIN>pip install py2neo Collecting py2neo Using cached https://files.pythonhosted.org/packages/cd/79/a77cc0ad86c021c25dac9f52a0cd33f6832c6af7fa5e58f4438d781ae9c3/py2neo-4.0.0.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\users\admin\appdata\local\temp\pip-install-xj8t67\py2neo\setup.py", line 25, in <module> from py2neo.meta import __author__, __email__, __license__, __package__, __version__ File "py2neo\__init__.py", line 19, in <module> from py2neo.data import * File "py2neo\data.py", line 26, in <module> from py2neo.cypher import LabelSetView, cypher_repr, cypher_str File "py2neo\cypher\__init__.py", line 36, in <module> from py2neo.internal.collections import SetView File "py2neo\internal\collections.py", line 24, in <module> from py2neo.internal.compat import bytes_types, string_types File "py2neo\internal\compat.py", line 45, in <module> DEVNULL = open(devnull, "rw") ValueError: Invalid mode ('rw') Command "python setup.py egg_info" failed with error code 1 in c:\users\admin\appdata\local\temp\pip-install-xj8t67\py2neo\ order_items。以下是我的模式示例

orders

create_table "orders", force: :cascade do |t|
 t.string "first_name"
 t.string "last_name"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
 t.string "token"
 t.decimal "sub_total"
 t.string "mobile"
 t.string "address"

对于型号,

create_table "order_items", force: :cascade do |t| t.integer "order_id", null: false t.integer "item_id", null: false t.integer "quantity", null: false t.decimal "price", precision: 15, scale: 2, null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end

order.rb

has_many :order_items

order_item.rb

我以为我可以通过此关联获得belongs_to :order belongs_to :item ,但无法获得。我收到Order.orderitem.quantity

错误

1 个答案:

答案 0 :(得分:0)

尝试Order.first.order_items 这将返回所有第一笔订单商品

然后您就可以遍历它们

Order.first.order_items.each do |item|
  item.quantity
  ....
end

或带索引取出项目

items = Order.first.order_items
items[0].quantity