rails: create Parent, if doesn't exist, whilte creating child record

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-01 07:47:16

问题


Any best practices for the following?:

I have Manufacturer model that has_many Inventory

In my new Inventory form I want a field that maps to Manufacturer.name so that when one submits the new Inventory form the app:

  • searches for a manufacturer with the 'name' from the form
    • if it exists then assign the id to @inventory.manufacturer_id and save @inventory
    • if it doesn't exist then create the manufacturer with the 'name' from the form, assign the id to @inventory.manufacturer_id and save
    • have validations work on the new Inventory form
      • such that, if the the Inventory form fails validation on a field other than 'name'
        • the 'name' field will be repopulated with whatever the user entered (but a new manufacturer is not created unless the form passes validation)

回答1:


You may try like this:

class Inventory < ActiveRecord::Base

  ...

  belongs_to :manufacturer

  ...

  def manufacturer_name
    manufacturer && manufacturer.name
  end

  def manufacturer_name=(value)
    self.manufacturer = Manufacturer.find_by_name(value)
    self.manufacturer ||= Manufacturer.new(:name => value)
  end

  ...

end

In this case you should output manufacturer_name text field on Inventory form.



来源:https://stackoverflow.com/questions/3588811/rails-create-parent-if-doesnt-exist-whilte-creating-child-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!