Rails: create a parent if it does not exist when creating a child entry

Any recommendations for the following ?:

I have a manufacturer model that has_many Inventory

In my new inventory form, I want the field to be mapped to the name Manufacturer.name, so when one submits a new inventory form to the application:

  • looking for a manufacturer named "name" from the form
    • if it exists, assign id @ inventory.manufacturer_id and save @inventory
    • if it does not exist then create a manufacturer with the name "name" from the form, assign id @ inventory.manufacturer_id and save
    • validations are valid in a new form of inventory
      • so that if the inventory form does not pass verification in a field other than the name,
        • the "name" field will be populated with what was entered by the user (but a new manufacturer is not created if the form does not pass the verification).
+3
source share
1 answer

You can try the following:

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 display the text field product_name in the Inventory form.

+3
source

Source: https://habr.com/ru/post/1762014/


All Articles