accepts_nested_attributes_for的自定义更新查找



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

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]

我找到了一个解决方案:

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

最新更新