Ruby on Rails的Has_Many:通过关联



我在使用ruby on rails时遇到了一些问题,特别是通过deal_event与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

有什么想法我做错了这两个错误弹出?谢谢。

您将需要在DealEvent模型中使用这一行:

attr_accessible :deal, :event

虽然如果它只是一个关系表(它看起来像),那么你不这样创建关系。使用嵌套表单等

相关内容

  • 没有找到相关文章

最新更新