0

我在使用 ruby​​ on rails 时遇到了一些问题,特别是通过 deal_event 建立与交易和事件的多对多连接。我已经检查了几个类似的 stackoverflow 问题,甚至http://guides.rubyonrails.org/但我仍然没有得到任何东西..

这是我的模型:

交易.rb

class Deal < ActiveRecord::Base
  has_many :deal_events
  has_many :events, :through => "deal_events"
  attr_accessible :approved, :available, :cents_amount, :dollar_amount, :participants, :type
end

事件.rb

class Event < ActiveRecord::Base
  has_many :deal_events
  has_many :deals, :through => "deal_events"
  attr_accessible :day, :image, :description, :location, :title, :venue, :remove_image
end

交易事件.rb

class DealEvent < ActiveRecord::Base
  belongs_to :deal
  belongs_to :event
end

这是我的迁移文件:

20130102150011_create_events.rb

class CreateEvents < ActiveRecord::Migration
  def change
    create_table :events do |t|
      t.string :title,     :null => false
      t.string :venue
      t.string :location
      t.text :description 
      t.date :day

      t.timestamps
    end
  end
end

20130112182824_create_deals.rb

class CreateDeals < ActiveRecord::Migration
  def change
    create_table :deals do |t|
      t.integer :dollar_amount
      t.integer :cents_amount
      t.integer :participants
      t.string  :type, :default => "Deal"
      t.integer :available
      t.string  :approved

      t.timestamps
    end
  end
end

20130114222309_create_deal_events.rb

class CreateDealEvents < ActiveRecord::Migration
  def change
    create_table :deal_events do |t|
      t.integer :deal_id, :null => false
      t.integer :event_id, :null => false

      t.timestamps
    end
  end
end

在我用一笔交易和一项事件播种我的数据库后,我进入控制台并输入

deal = Deal.first # ok
event = Event.first # ok

DealEvent.create(:deal => deal, :event => event) # Error: ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: deal, event

deal.events # Error: ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association "deal_events" in model Deal

关于弹出这两个错误我做错了什么的任何想法?谢谢。

4

1 回答 1

1

您的 DealEvent 模型中需要此行:

attr_accessible :deal, :event

尽管如果它只是一个关系表(看起来像),那么您就不会以这种方式创建关系。使用嵌套表格等。

于 2013-01-15T02:33:09.190 回答