我試圖導入json數據來填充由志願者組織和志願者機會組成的數據庫。我想標記所有的組織以及所有的機會。我正在使用多態關聯將組織和機會模型關聯到標記模型。我最終希望創建一個測驗,它將逐步構建一組關鍵字,然後我可以使用這些關鍵字與組織和商機標記進行比較以返回有用的結果。播種嵌套的JSON數據並進行多態關聯
我對此很新,我甚至不確定這是否是一種有效的方式。我有一個json數據日誌,我想將其放入postgresql數據庫,並且遇到問題的位置是嘗試對數據進行種子處理。
模型
class Organization < ActiveRecord::Base
has_many :tags, as: :taggable
has_many :opportunities
end
class Opportunity < ActiveRecord::Base
has_many :tags, as: :taggable
belongs_to :organization
end
class Tag < ActiveRecord::Base
belongs_to :taggable, polymorphic: true
end
遷移
class CreateOpportunities < ActiveRecord::Migration
def change
create_table :opportunities do |t|
t.string :name
t.belongs_to :organization
t.timestamps null: false
end
end
end
class CreateOrganizations < ActiveRecord::Migration
def change
create_table :organizations do |t|
t.string :name
t.timestamps null: false
end
end
end
class CreateTags < ActiveRecord::Migration
def change
create_table :tags do |t|
t.string :name
t.references :taggable, polymorphic: true, index: true
t.timestamps null: false
end
end
end
樣品嵌套JSON
[
{
"name": "A Child’s Place",
"tags":
[
"children-and-teens",
"homelessness",
"education",
"seniors"
],
"opportunities":
[
{
"name": "Snack Packs",
"tags":
[
"indirect",
"group",
"food-preparation",
"homelessness",
"ongoing",
"one-time"
]
},
{
"tags":
[
"group",
"indirect",
"office",
"ongoing"
]
}
]
},
{
"name": "Aldersgate",
"tags":
[
"seniors"
],
"opportunities":
[
{
"name": "test opp",
"tags":
[
"direct",
"test",
"recurring"
]
}
]
}
]
所以從這個數據,我通過循環數組中的每個對象,然後創建組織對象在循環每個標籤,並通過鏟它將它添加到organization.tags
當在每個組織內循環遍歷每個機會時,我想創建該機會對象並將其鏟入組織。機會。同樣,我將循環訪問每個商機的標籤數組,找到這些標籤並將它們鏟入該機會標籤。
這裏是我的seed.rb這裏,我試圖做到這一點,使協會
tags = [...] #array of tag strings
tags.each do |tag|
Tag.create(name: tag)
end
json = File.read('db/org.json')
data = JSON.parse(json)
data.each do |org|
x = Organization.create(name: org["name"])
org["tags"].each do |tag|
x.tags << Tag.find_by(name: tag)
end
org["opportunities"].each do |opportunity|
y = Opportunity.create(name: opportunity["name"])
opportunity["tags"].each do |tag|
y.tags << Tag.find_by(name: tag)
end
x.opportunities << y
end
end
當我運行 耙分貝:種子
我從線路收到此錯誤在哪裏「M通過的機會
NoMethodError: undefined method `each' for nil:NilClass
迭代但是當我把在binding.pry和步,沒有什麼是即將到來的零,所以我很納悶
這可能是如此錯誤和愚蠢,我等了很長時間才發佈這個,因爲我知道它可能是狗屎,但我只是卡住了。如果您有任何關於如何更好地完成我想要做的事情的指示,或者只是關於這些事情的一般指針,我會非常感激。
更新
我已經LINTED JSON數據,一切似乎無慾無求,但是當我去到控制檯通過去
Organization.first.opportunities.first.tags
我收到回只有3個檢查協會標籤:食物準備,無家可歸和一次性,所以並非所有的機會標籤都相關聯。也許我需要在每個關聯期間分配標籤類型...
謝謝。代碼linting非常有幫助! – Dirtsquad