class Organization < ActiveRecord::Base
has_many :doctors
end
class Doctor < ActiveRecord::Base
belongs_to :organization
end
确保你有organization_id
你写的那样,然后你可以做(只是作为一个例子):
@doctor = Doctor.first
@doctor.organization
@organization = Organization.first
@organization.doctors
更新
你不能用类似的东西填充数据库:
Doctor.where(name: "Frank", specialization: "Rubber Duck Surgery").first_or_create
还没有尝试过,但它可能比遍历复杂的数组更容易:
@organization = Organization.where(name: "Surgeons").first_or_initialize
["Bob", "Frank", "Harry"].each do |name|
@organization.doctors.where(name: name).first_or_initialize
end
@organization.save
更新
好的,以下内容如何:
@doctor_names = ["Bob", "Rob", "Fred", "Bill"]
@doctor_salaries = [10000, 15000, 30000, 400]
def return_array_of_hashes(*data)
array = []
data[1].each_with_index do |d, i|
hash = {}
(0...data.count).to_a.in_groups_of(2).each do |a,b|
hash.merge!({data[a] => data[b][i]})
end
array << hash
end
array
end
@doctors_array = return_array_of_hashes("name", @doctor_names, "salary", @doctor_salaries)
# => [{"name"=>"Bob", "salary"=>10000}, {"name"=>"Rob", "salary"=>15000}, {"name"=>"Fred", "salary"=>30000}, {"name"=>"Bill", "salary"=>400}]
@doctors_array.each do |hash|
Doctor.where(hash).find_or_create
end
这样,您可以对正在创建的任何模型使用相同的方法,并且可以轻松地将更多数据添加到数组中。只需确保以key
then的正确顺序添加数据value
。
您可能需要检查所有数组的大小是否相同,尽管您的模型验证可能会丢弃任何无效数据。