Ruby on Rails Has_Many:通过关联

时间:2013-01-15 02:30:42

标签: ruby-on-rails-3

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

以下是我的模特:

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

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

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

对于这两个错误弹出来我错误的想法?感谢。

1 个答案:

答案 0 :(得分:1)

你的DealEvent模型中需要这一行:

attr_accessible :deal, :event

虽然它只是一个关系表(它看起来像),但你不会以这种方式创建关系。使用嵌套表格等。