2016-02-09 47 views
0

在rails中存在多對多關係時遇到了一些問題。我有三個情態動詞:Rails has_many:通過,未定義的方法

  1. 訂購
  2. 項目
  3. 逐項

定單已經通過逐項反之亦然許多項目。

查詢Item.find(1).orders工作正常,但是當我嘗試Order.find(1).items它返回:

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

這裏是我的代碼:

Schema.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 

不知道,也許它的干擾,但也有一個店模式,和商店有許多訂單。

感謝您的幫助和時間!

+0

'Order.find(1).itemized'返回什麼? – rdnewman

+0

,#<分類ID:2,item_id:2,order_id:1,數量:1,created_at:」2016-02-10 03:31:53「,updated_at:」2016- 02-10 03:31:53「>]> – MrBalloons

回答

0

如果我看多對多協會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

+0

這個工作,對我來說很可怕的命名。 – MrBalloons