0

我有 2 个模型UnitPlatePlantPlate它们是 STI(单表继承)的一部分。我需要与他们进行多对多关联。has_many: through 和 STI 的以下方式是否正确。我有以下型号。使用以下方法在迁移中遇到一些问题

Parent Model

class Plate < ActiveRecord::Base

end

Submodel 1

class UnitPlate < Plate

  has_many :unit_and_plant_plates, :dependent => :destroy
  has_many :plant_plates, through: :unit_and_plant_plates

end

Submodel 2

class PlantPlate < Plate

  has_many :unit_and_plant_plates, :dependent => :destroy
  has_many :unit_plates, through: :unit_and_plant_plates

end

Associated Model

class UnitAndPlantPlate < ActiveRecord::Base
    belongs_to :unit_plate
    belongs_to :plant_plate
end

Migration

class CreateTableUnitAndPlantPlates < ActiveRecord::Migration
  def change
     create_table :unit_and_plant_plates do |t|
      t.belongs_to :unit_plate
      t.belongs_to :plant_plate
      t.timestamps
     end
    add_index :unit_and_plant_plates, :unit_plate_id
    add_index :unit_and_plant_plates, :plant_plate_id
   end
end

迁移期间的错误

rake aborted!
/Users/ankitgupta/.rvm/gems/ruby-1.9.3-p392/gems/rake-10.1.0/lib/rake/trace_output.rb:16:in `block in trace_on': invalid byte sequence in US-ASCII (ArgumentError)
    from /Users/ankitgupta/.rvm/gems/ruby-1.9.3-p392/gems/rake-10.1.0/lib/rake/trace_output.rb:14:in `map'
    from /Users/ankitgupta/.rvm/gems/ruby-1.9.3-p392/gems/rake-10.1.0/lib/rake/trace_output.rb:14:in `trace_on'
    from /Users/ankitgupta/.rvm/gems/ruby-1.9.3-p392/gems/rake-10.1.0/lib/rake/application.rb:340:in `trace'
    from /Users/ankitgupta/.rvm/gems/ruby-1.9.3-p392/gems/rake-10.1.0/lib/rake/application.rb:187:in `display_error_message'
    from /Users/ankitgupta/.rvm/gems/ruby-1.9.3-p392/gems/rake-10.1.0/lib/rake/application.rb:174:in `rescue in standard_exception_handling'
    from /Users/ankitgupta/.rvm/gems/ruby-1.9.3-p392/gems/rake-10.1.0/lib/rake/application.rb:165:in `standard_exception_handling'
    from /Users/ankitgupta/.rvm/gems/ruby-1.9.3-p392/gems/rake-10.1.0/lib/rake/application.rb:75:in `run'
    from /Users/ankitgupta/.rvm/gems/ruby-1.9.3-p392/gems/rake-10.1.0/bin/rake:33:in `<top (required)>'
    from /Users/ankitgupta/.rvm/gems/ruby-1.9.3-p392/bin/rake:19:in `load'
    from /Users/ankitgupta/.rvm/gems/ruby-1.9.3-p392/bin/rake:19:in `<main>'
    from /Users/ankitgupta/.rvm/gems/ruby-1.9.3-p392/bin/ruby_noexec_wrapper:14:in `eval'
    from /Users/ankitgupta/.rvm/gems/ruby-1.9.3-p392/bin/ruby_noexec_wrapper:14:in `<main>'

这种通过正确定义has_many的方式吗?

4

1 回答 1

0

尝试这个:

class CreateTableUnitAndPlantPlates < ActiveRecord::Migration
  def change
     create_table :unit_and_plant_plates do |t|
      t.integer :unit_plate_id
      t.integer :plant_plate_id
      t.timestamps
     end
    add_index :unit_and_plant_plates, :unit_plate_id
    add_index :unit_and_plant_plates, :plant_plate_id
   end
end
于 2013-07-31T12:48:08.223 回答