이것은 아마도 기본적인 질문 일뿐입니다 만 현재는 내게 열매를 맺고 있습니다 ... 아마도 코드가 너무 깊기 때문에 뭔가 빠졌을 것입니다. 그러나 질문은연관을 가진 새로운 루비 모델 인스턴스를 생성하십시오
입니다.연결을 사용하여 개체를 만들려면 어떻게해야합니까?
내가 다음 마이그레이션 스크립트 한 :이 개체에 대한class CreateConcepts < ActiveRecord::Migration
def self.up
create_table :concepts do |t|
t.integer :language_id, :null => false
t.string :uri
t.integer :isco_code
t.timestamps
end
end
def self.down
drop_table :concepts
end
end
class CreatePrefLabels < ActiveRecord::Migration
def self.up
create_table :pref_labels do |t|
t.integer :language_id
t.integer :concept_id
t.string :value
t.timestamps
end
end
def self.down
drop_table :pref_labels
end
end
class CreateLanguages < ActiveRecord::Migration
def self.up
create_table :languages do |t|
t.string :code
t.timestamps
end
end
def self.down
drop_table :languages
end
end
클래스는 다음과 같이 : 내가 제대로 내 루비의 교훈을 기억한다면
class Concept < ActiveRecord::Base
belongs_to :language
has_one :pref_label
validates_uniqueness_of :isco_code
end
class PrefLabel < ActiveRecord::Base
belongs_to :language
belongs_to :concept
validates_uniqueness_of :value
end
class Language < ActiveRecord::Base
has_many :concepts
has_many :pref_labels
validates_uniqueness_of :code
end
, 다음 코드는 완벽해야한다 괜찮음 :
concept = Concept.first
concept.pref_label
language = Language.find(:code => "en")
language.pref_labels
language.concepts
그래서 다음 코드 줄을 작성했습니다. 내부가 조금 어두워 보이지만 JSON 데이터에서 생성 된 해시가 올바른지 100 % 확신합니다. 디버거 이것을 검사 : 1) 모든 시간 2 생성에 beeing되지 않음) 내 개념 객체에 연결되지 않습니다 :
# This function will retrieve all the top most concepts from the ESCO API in the
# specified language as an array of Ruby objects, each represented by the relevant class.
# If the relevant concept does not exist in the database, the entry is automatically created.
# The function will fall back to English by default if no language is specified
def self.top_concepts(lang = Language.find_by_code('en') || Language.create(:code => 'en'))
concepts = []
json = HTTParty.get "#{Setting[:api]}/getTopmostConcepts?language=#{lang.code}"
collection = JSON.parse json.parsed_response
collection.each do |c|
language = Language.find_by_code c['language'] || Language.create(:code => c['language'])
concept = Concept.create(:language => language, :uri => c['uri']['uri'], :isco_code => c['iscoCode'].to_i)
label = PrefLabel.find_by_concept_id(concept.id) || PrefLabel.create(:language_id => language.id, :concept_id => concept.id, :value => c['prefLabel']['string'])
concept.pref_label= label
concept.save
concepts << concept
end
return concepts
end
지금 데 문제는 내 PrefLabels이 있다는 것입니다.
무엇이 누락 되었습니까?
맞아요, 범위가 누락되었습니다. –