2016-04-14 30 views
1

因此,我被要求在Rails中爲現有模型添加新的分類。我的第一個模型,讓我們假設帖子需要獲得與新興趣模型的多對多關係,其中存儲了某些興趣領域。每篇文章可以有0到很多這些興趣。此外,在上線時,這些利益已經被確定爲10個利益的固定清單。在生產中將模型添加到應用程序的最佳方式

什麼是創建新模型的最佳方式,並預先填充10個固定感興趣區域的表格?

我正在考慮使用種子填充數據庫,但我並沒有真正體驗過它。這是正確的路嗎,還是我在這裏錯過了什麼?

回答

1

由於您的應用程序在實際生產環境中運行,以創建行,這將是最好創建該表並通過遷移構建默認關聯。對數據庫進行種子管理只能在創建數據庫時發生,否則可能會引入重複數據。

class CreateInterests < ActiveRecord::Migration 
    def migrate(direction) 
    super 

    if direction == :up 
     ['Iterest 1', 'Interest 2', ..., 'Interest N'].each do |name| 
     Interest.create(name: name) 
     end 

     interests = Interest.all 

     Post.all.each do |post| 
     post.interests << interests 
     end 
    end 
    end 

    def change 
    create_table :interests do |t| 
     t.integer :name 
     t.timestamps null: false 
    end 

    create_table :interests_posts, :id => false do |t| 
     t.integer :interest_id 
     t.integer :post_id 
    end 

    add_index :interests_posts, [:interest_id, :post_id] 
    end 
end 
+0

這是假設所有職位將屬於所有類別。我懷疑這是OP想要的初始狀態。 – SteveTurczyn

+0

@steveTurczyn我對問題的理解方式是創建興趣模型,在興趣 - 帖子之間創建一個HABTM連接表,創建一組默認的興趣並將它們與帖子關聯。 – KPheasey

+0

我同意OP希望HABTM,但如果所有帖子都有興趣,該功能有什麼意義?他可能想在創建新模型和能力之後,將職位與崗位上的興趣相關聯。 – SteveTurczyn

0

您可以使用種子,但對於如此少量的初始興趣對象,我只需在遷移中完成。

建立興趣模型app/models/interest.rb第一,然後生成遷移和編輯它,當你做rake db:migrate

class CreateInterests < ActiveRecord::Migration 
    def up 
    create_table :interests do |t| 
     t.string :name 
     t.timestamp 
    end 
    Interest.create(name: "Animals") 
    Interest.create(name: "Flowers") 
    Interest.create(name: "Dinosaurs") 
    # add seven more interests... 
    end 

    def down 
    drop_table :interests 
    end 
end 
相關問題