使用现有数据创建has_many / belongs_to

时间:2012-06-19 12:32:59

标签: ruby-on-rails

我想将Model.attribute转换为Attribute.models。

e.g。我目前有Model.first.attribute => "string",我想将belongs_to :attributes添加到Model.rb中,然后在创建Attribute.rb之后添加has_many :models

我在Model表中添加了一个列:attribute_id,我正在尝试做类似的事情

Model.each do |m|
  a = Attribute.find_or_create_by_name(m.attribute)
  m.update_attribute("attribute_id", a.id)
end

这是完成此任务的正确方法吗?

1 个答案:

答案 0 :(得分:0)

如果模型has_many :attributes(和属性belongs_to :model),则属性模型中应该有model_id

然后你可以做

Model.all.each do |m|
  m.attributes.create!(:name => m.attribute) unless m.attributes.find_by_name(m.attribute)
end

<强>更新

你所做的对我来说似乎没问题。唯一的问题是,您有一个列attribute而另一个列在名为attribute_id的列中,其中belongs_to位于模型中。当你输入Model.first.attribute时,我不知道ActiveRecord会如何反应。