【问题标题】:RoR - check if record exist before buildRoR - 在构建之前检查记录是否存在
【发布时间】:2014-09-03 23:30:13
【问题描述】:

我有两个模型

地址.rb 属于_to :zip 接受_nested_attributes_for :zip 压缩包.rb has_many :地址

在新地址的表单上,我还创建了一个 Zip。但我想检查插入的 Zip 是否已经存在。如果是,它应该返回现有的 Zip,如果不是,它应该创建一个新的

地址控制器 定义新 @address = 地址.new @address.build_zip 结尾

我在 StackOverFlow 上看到了类似的 question,但没有我想要的答案……有人建议:

before_create :check_zip_exists def check_zip_exists @zip = Zip.find_by_cp1_and_cp2(self.cp1, self.cp2) 如果@zip!=nil # 结尾 结尾

# 应该是什么才能将现有的 Zip 与地址相关联,而不是创建一个新的?

【问题讨论】:

  • 我看不出这与您所说的重复。正如我在问题中所说,它与另一个没有完整答案的 question 重复,这就是我再次询问的原因
  • 是的,这也是一个骗局。大概还有 50 个人...@address.zip = Zip.find_or_create_by...
  • 这不是骗人的,因为没有一个问题可以作为有效的答案。如果您愿意,可以检查它...find_or_create_by 不起作用,因为我想根据两个参数查找并使用 6 个参数创建...但是感谢您的参与

标签: ruby-on-rails nested-attributes


【解决方案1】:

这样做的方式是这样安排的:

地址.rb 属于_to :zip Accept_nested_attributes_for :zip, :reject_if => :check_zip_exists 私人的 def check_zip_exists(归属) cp1 = 属性['cp1'] cp2 = 属性['cp2'] zip = Zip.where(:cp1=>cp1, :cp2=>cp2).first 如果 zip.nil? 返回假 别的 self.zip_id = zip.id 结尾 结尾

【讨论】:

    【解决方案2】:

    尝试类似:

    zip = Zip.where(field: value).first_or_create
    

    更新

    当您使用accepts_nested_attributes_for :zip 时,内部会生成一个名为zip_attributes=(attributes) 的公共方法。

    此方法调用私有方法(取决于关系是集合还是单个对象),在您的情况下,调用的私有方法是assign_nested_attributes_for_one_to_one_association

    因此,您可以覆盖 Address 模型中的 public_method zip_attributes=(attributes) 以替换正常行为:

    def zip_attributes=(attributes)
      self.zip = Zip.where(attributes).first_or_create #you can change attributes to be the fields that you need to find the correct zip
    end
    

    更新 2

    def zip_attributes=(attributes)
      cp1 = attributes.delete(:cp1)
      cp2 = attributes.delete(:cp2)
      self.zip = Zip.where(cp1: cp1, cp2: cp2).first_or_create(attributes)
    end
    

    【讨论】:

    • 这会返回现有的 Zip 而不是创建一个新的吗?
    • 是的,它会返回现有的 Zip
    • 我应该把它放在哪里?
    • 非常感谢您的帮助,但我没有设法让它像那样工作,因为我需要基于两个属性(:cp1 和:cp2)但如果它不存在我需要创建 6 个属性(:cp1、:cp2 和其他...)
    • 好的,我已经更新了一次我的答案,你看看。
    猜你喜欢
    • 2012-03-06
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多