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

后端 未结 1 996
梦毁少年i
梦毁少年i 2021-01-14 04:01

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.na

相关标签:
1条回答
  • 2021-01-14 04:13

    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.

    0 讨论(0)
提交回复
热议问题