我试图为has_and_belongs_to_many关联手动构建中间表

时间:2016-11-28 23:53:36

标签: ruby-on-rails-4 ruby-on-rails-4.2

我需要为很多人查找生成一个表(我认为它应该是HABTM,因为查找的简单性质。一个工厂可以有一个或多个月的时间开花,并且所有月份都会有许多植物盛开。

我目前的工厂数据有一个" flower_time"列以逗号分隔的缩写。对于每个工厂,我都要遍历我需要在months_plants表中添加一个新行。

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来定义它

1 个答案:

答案 0 :(得分:1)

Month_plant应替换为MonthPlant