accepts_nested_attributes_for的自定义更新查找

时间:2012-04-17 23:44:10

标签: ruby-on-rails activerecord

我有一个大多数静态的设备表,如下所示:

class CreatePlatforms < ActiveRecord::Migration
  def change
    create_table :platforms do |t|
      t.column :model, :string, :null => false
      t.column :name, :string, :null => false

      t.timestamps
    end

    add_index :platforms, :model, :unique => true

    Platform.create  :model => "iPhone1,1", :name => "Original iPhone"
    Platform.create  :model => "iPhone1,2", :name => "iPhone 3G"
    [...]
  end
end

引用平台的表格,设备。现在我想将模型发送到服务器,并将创建的设备链接到数据库中该模型的相应ID,类似于accepts_nested_attributes_for :platform。但是,除非属性中有id,否则会创建记录。

使用不同的属性来查找现有记录,是否有accepts_nested_attributes_for或类似的方法?

我可以在控制器中手动将其交换出来,如下所示,但这样做很麻烦而且是最后的手段:

params[:device][:platform] = Platform.find_by_model params[:device][:platform_attributes][:model]

1 个答案:

答案 0 :(得分:1)

我找到了解决方案:

def autosave_associated_records_for_platform
  if new_platform = Platform.find_by_model(platform.model) then
    self.platform = new_platform
  else
    self.platform.name = "Unknown"
    self.platform.save!
  end
end