我正在尝试为 has_and_belongs_to_many 关联手动构建中介 table

I'm trying to manually build an intermediary table for a has_and_belongs_to_many association

我需要生成一个 table 用于多对多查找(我认为它应该是一个 HABTM,因为查找的性质很简单。一个植物可以有一个或多个月,其中它开花,所有月份都会有许多植物开花。

我当前的植物数据有一个 "flower_time" 列,其中缩写以逗号分隔。对于每株植物,我遍历我需要在 months_plants table.

中添加一个新行

month_plant.rb

class CreateMonthPlants < ActiveRecord::Migration
  def change
     create_table :month_plants, id: false do |t|
      t.integer :month_id, index: true
      t.integer :plant_id, index: true
    end
  end

  def drop
    drop_table :month_id
  end
end

plant.rb

class Plant < ActiveRecord::Base
  belongs_to :detail
  has_and_belongs_to_many :months
end

month.rb

class Month < ActiveRecord::Base
  has_and belongs_to_many :plants
end

month_plant.rb

class MonthPlant < ActiveRecord::Base
  belongs_to :month
  belongs_to :plant
end

XXX_controller

  def common
    c = 0
    @plants = Plant
      .order(:id)
    @plants.each do | p|
      if p.flower_time == "Not of Interest"
       bloom = Month_plant.create(plant_id: p.id, "month_id = 13")
        c += 1
      end 
      if p.flower_time == "Unknown"
       bloom = Month_plant.create(:plant_id => p.id, "month_id = 14")
        c += 1
      end 
      if p.flower_time != "Not of Interest" and p.flower_time != "Unknown" 
        a = p.flower_time.split ','
        a.each do | b |
          m = case (b)
            when 'Jan' then 1
            when 'Feb' then 2
            when 'Mar' then 3
            when 'Apr' then 4
            when 'May' then 5
            when 'Jun' then 6
            when 'Jul' then 7
            when 'Aug' then 8
            when 'Sep' then 9
            when 'Oct' then 10
            when 'Nov' then 11
            when 'Dec' then 12
          end
          bloom = Month_plant.create(:plant_id => p.id, 'month_id = ?", m)
          c += 1
        end 
      end 
      @cc = c
   end
end

我知道上面的代码不漂亮,但是当我输出到屏幕时逻辑有效。当我尝试输出到数据库时,出现以下错误: 无法自动加载常量 Month_plant,需要 c:/Sites/sg2017/app/models/month_plant.rb 来定义它

Month_plant 应替换为 MonthPlant