rails:创建父级,如果不存在,则创建子级记录 [英] rails: create Parent, if doesn't exist, whilte creating child record

查看:61
本文介绍了rails:创建父级,如果不存在,则创建子级记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有以下最佳做法?

我的制造商模型具有很多库存

I have Manufacturer model that has_many Inventory

在我的新清单表单中,我想要一个映射到Manufacturer.name的字段,以便当一个 提交新清单的应用程序:

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:

  • 从表格中搜索带有名称"的制造商
    • 如果存在,则将ID分配给@ inventory.manufacturer_id并保存@inventory
    • 如果不存在,则从表单中使用名称"创建制造商,将ID分配给@ inventory.manufacturer_id并保存
    • 在新的库存表单上进行了验证
      • 这样,如果库存"表单在名称"以外的其他字段上的验证失败
        • 名称"字段将用用户输入的任何内容重新填充(但除非表单通过验证,否则不会创建新的制造商)
        • 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)

              推荐答案

              您可以这样尝试:

              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.

              这篇关于rails:创建父级,如果不存在,则创建子级记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆