2017-04-02 37 views
-1

我有兩個模型,Project和Todo。從燈具加載數據到數據庫(關聯)

項目存儲Todos數組。

移民項目:

def up 
    create_table :projects do |t| 
     t.string :title, null: false 
     t.timestamps null: false 
    end 
    end 

移民TODO:

def up 
    create_table :todos do |t| 
     t.string :text, null: false 
     t.boolean :isCompleted, null:false 
     t.integer :project_id, null:false 
     t.timestamps null: false 
    end 
    end 

project.rb

class Project < ActiveRecord::Base 
    has_many :todos 
end 

todo.rb

class Todo < ActiveRecord::Base 
    belongs_to :project 
end 

projects.yml

family: 
    title: 'Семья' 

work: 
    title: 'Работа' 

therest: 
    title: 'Прочее' 

todos.yml

family_todos: 
    text: 'Купить молоко' 
    isCompleted: false 
    project_id: family 

work_todos: 
    text: 'Закончить проект' 
    isCompleted: false 
    project_id: work 

therest_todos: 
    text: 'Познать бесконечность' 
    isCompleted: true 
    project_id: therest 

我怎樣才能將它們連接正確,所以當我把一個項目,我可以看到它裏面的所有的待辦事項?另外我很好奇我怎麼能通過像數組這樣的yml文件添加日期?

回答

0

其中一個更好的方式來鏈接表之間的關聯是通過引用。你可以這樣做到你的todos表

def up 
create_table :todos do |t| 
    t.string :text, null: false 
    t.boolean :isCompleted, null:false 
    t.references :project, references: :projects, index: true, foreign_key: true 
    t.timestamps null: false 
end 
end 

這將在你的todos表中創建一個名爲project_id的字段。因此你有一個has_many todos的項目表。

有幾種不同的方法可以預加載數據庫。您可以使用seeds.rb文件,您可以在其中編寫代碼以從yml文件讀取並加載到數據庫。 如果你把所有的家庭待辦事項的陣列可以做這樣的事情

proj = Project.create(title: family) 

,那麼你可以把它放在數據庫這樣

##Family todos 
loop through 
    proj.todos << Todo.create(...fields...) 
end 
+0

你能回答我 - 我我怎麼能得到所有的todos?例如,我需要從我的家庭項目中打印所有待辦事項。 <%= project.todos。 。 。%> – NanoBreaker

+0

你可以做<%= Project.where(title:「family」)。todos%> –

0

如果你想預先填寫你的數據庫,那麼更好的方法是使用seeds.rb,它位於db/

簡單地在這裏和類使用紅寶石從Rails應用程序,例如,創建一個項目,待完成它:

project = Project.create!(...) 
project.todos.create!(...) 

然後只需運行rake db:seed來執行它。

您可以在這裏的例子瞭解更多:http://www.xyzpub.com/en/ruby-on-rails/3.2/seed_rb.html