ActiveRecord / Ruby - has_many通过has_one

时间:2015-07-31 17:56:39

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord

我有一个Event模型,其中需要items。示例事件可能包含10个票证和5个气球,其中票证和气球属于Item模型。我设置了它,以便有一个ItemDatum模型,它包含一个事件中的所有items以及一个跟踪每个项目有多少的哈希值。

我的问题出在Event模型关联中,我有:

class Event < ActiveRecord::Base
    belongs_to :location

    has_one :item_datum, dependent: :destroy
    has_many :items, through: :item_datum, source: :event
end

但是在尝试向@event.items var添加项目时,我收到错误:Could not find the association :item_datum in model Event

这是我的Event迁移:

class CreateEvents < ActiveRecord::Migration
  def change
    create_table :events do |t|
      t.string :name
      t.string :text

      t.integer :location_id
      t.integer :item_datum_id

      t.timestamps null: false
    end
  end
end

Item型号:

class Item < ActiveRecord::Base
    belongs_to :item_datum

    validates :name, presence: true, length: { minimum: 1 }
    validates :description, presence: true
    validates :item_type, presence: true

end

ItemDatum型号

class ItemDatum < ActiveRecord::Base
    belongs_to :event
    has_many :items
end

我试图将items添加到event,如此:

@event = Event.first;
@item = Item.first;
@event.items << @item;

0 个答案:

没有答案
相关问题