2016-11-28 63 views
0

我需要爲許多查找生成一個表(我認爲它應該是HABTM,因爲查找的簡單性。植物可以有一個月或幾個月開花,並且所有月份都會有很多植物在其中開花我想爲has_and_belongs_to_many關聯手動構建中間表

我目前的植物數據有一個逗號分隔縮寫的「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

Month_plant應代之以MonthPlant

+0

這不提供問題的答案。要批評或要求作者澄清,請在其帖子下方留言。 - [來自評論](/ review/low-quality-posts/14434888) – Vikrant

+0

他已經建立了正確的關係,並表示邏輯起作用,但他在模型命名上出錯,所以他只需要修復它。爲什麼它不是一個答案? – Thanh

+0

沒關係,你發現了確切的問題,但是'MonthPlant'這個名字會起作用嗎?任何解釋... – Vikrant

相關問題