mysql - Rails has_many :through, 未定义方法

标签 mysql ruby-on-rails has-many-through

在处理 Rails 中的多对多关系时遇到一些问题。我有三个模式:

  1. 订单
  2. 项目
  3. 逐项列出

一个订单通过逐项列出多个项目,反之亦然。

查询 Item.find(1).orders 工作正常,但是当我尝试 Order.find(1).items 时它返回:

NoMethodError: undefined method `items' for #<Order:0x007fcad3bb3258>

这是我的代码:

架构.rb

create_table "itemizeds", force: :cascade do |t|
  t.integer  "item_id",    limit: 4
  t.integer  "order_id",   limit: 4
  t.integer  "quantity",   limit: 4
  t.datetime "created_at",           null: false
  t.datetime "updated_at",           null: false
end

create_table "items", force: :cascade do |t|
  t.string   "title",      limit: 255
  t.datetime "created_at",             null: false
  t.datetime "updated_at",             null: false
end

create_table "orders", force: :cascade do |t|
  t.integer  "customer_id", limit: 4
  t.integer  "store_id",    limit: 4
  t.integer  "order_id",    limit: 4
  t.datetime "created_at",                                    null: false
  t.datetime "updated_at",                                    null: false
  t.decimal  "price",                 precision: 8, scale: 2
  t.decimal  "discount",              precision: 8, scale: 2
end

Order.rb(模型)

class Order < ActiveRecord::Base
  has_many :itemized
  has_many :items, :through => :itemized
end

Item.rb(模型)

class Item < ActiveRecord::Base
  has_many :itemized
  has_many :orders, :through => :itemized
end

Itemized.rb(模型)

class Itemized < ActiveRecord::Base
  belongs_to :item
  belongs_to :order
end

不确定是否会造成干扰,但还有商店模型,并且商店有很多订单。

感谢您的帮助和时间!

最佳答案

如果我查看 http://guides.rubyonrails.org/association_basics.html 中的多对多关联我明白了

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, through: :appointments
end

所以我认为这是一个多元化的问题。尝试使用 :through => :itemizeds 代替。

关于mysql - Rails has_many :through, 未定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35303355/

相关文章:

sql - 获取 2 个 mySQL 表差异的更简单方法?

php - 查询时auto_increment默认值为NULL的列

ruby-on-rails - 是否可以在本地重现429错误(请求过多)?

ruby-on-rails-4 - ActiveAdmin has_many 通过关系不更新参数 Rails

activerecord - Yii框架中有类似 "has_one :through (from Rails)"的东西吗?

ruby-on-rails - 在 has_many :through relationships 中使用 collection<<object 函数时如何获取中间对象

c# - 如何在c#中动态组合两个或多个DataTable

html - 如何在两行中显示用户数据

ruby-on-rails - 如何在关闭 pry 的情况下启动 rails 控制台?

ios - 如何保护 JSON API 不被我的 iOS 客户端以外的任何人访问?