【问题标题】:Modify Nested attribute array before_save修改嵌套属性数组 before_save
【发布时间】:2014-03-08 21:10:42
【问题描述】:

我正在尝试在将嵌套属性保存到我的数据库之前对其进行修改。这个想法是,如果有人已经在服装数据库中提交了带有给定cid 的服装,我们应该提取那个并将其用于当前协议。但是,通过调试,我发现嵌套的属性数组根本没有改变。有什么想法吗?

谢谢! 马特

app/models/agreement.rb
class Agreement < ActiveRecord::Base
  before_save :get_costumes

  has_and_belongs_to_many :costumes, join_table: :agreement_costumes  
  accepts_nested_attributes_for :costumes, reject_if: proc { |attributes| attributes['cid'].blank? }

  has_many :drycleans
  accepts_nested_attributes_for :drycleans, allow_destroy: true, reject_if: :all_blank

  def get_costumes
    self.costumes.map! { |costume|
      unless Costume.where(cid: costume.cid).nil?
        Costume.where(cid: costume.cid).first
      end
    }
  end

end

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-4 nested-attributes


    【解决方案1】:

    您的除非条件永远不会是true。使用 where 语句,您始终会获得 ActiveRecord。还有一个空的 ActiveRecord 不是nil

    尝试将条件更改为:

    unless Costume.where(cid: costume.cid).count == 0
    

    或者到:

    unless Costume.find_by_cid(costume.cid).nil?
    

    【讨论】:

    • 问题不在于除非条件,我们可以解决。但是即使我返回一个值,costume 的值也不会改变。
    • 进行了更改,但仍然没有运气。
    猜你喜欢
    • 2021-10-27
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多