加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – rails – 左移“<<”运算符自动保存记录

发布时间:2020-12-16 21:32:46 所属栏目:百科 来源:网络整理
导读:需要帮助理解这段代码,据我所知,我知道“”附加到集合但在这里它正确保存记录,如果不调用.save方法怎么办? #user.rb has_many :saved_properties,through: :property_saves,source: :property#users_controller.rbdef update if @user.saved_properties Pro
需要帮助理解这段代码,据我所知,我知道“<<”附加到集合但在这里它正确保存记录,如果不调用.save方法怎么办?
#user.rb
 has_many :saved_properties,through: :property_saves,source: :property

#users_controller.rb
def update
  if @user.saved_properties << Property.find(params[:saved_property_id])
        render plain: "Property saved"
end

解决方法

也许查看源代码会对你有所帮助.这是我基于<<<<<<< activerecord中的方法:
def <<(*records)
  proxy_association.concat(records) && self
end

rails/collection_proxy.rb at 5053d5251fb8c03e666f1f8b765464ec33e3066e · rails/rails · GitHub

def concat(*records)
  records = records.flatten
  if owner.new_record?
    load_target
    concat_records(records)
  else
    transaction { concat_records(records) }
  end
end

rails/collection_association.rb at 5053d5251fb8c03e666f1f8b765464ec33e3066e · rails/rails · GitHub

def concat_records(records,should_raise = false)
  result = true

  records.each do |record|
    raise_on_type_mismatch!(record)
    add_to_target(record) do |rec|
      result &&= insert_record(rec,true,should_raise) unless owner.new_record?
    end
  end

  result && records
end

rails/collection_association.rb at 5053d5251fb8c03e666f1f8b765464ec33e3066e · rails/rails · GitHub

def insert_record(record,validate = true,raise = false)
    set_owner_attributes(record)
    set_inverse_instance(record)

    if raise
      record.save!(validate: validate)
    else
      record.save(validate: validate)
    end
  end

https://github.com/rails/rails/blob/5053d5251fb8c03e666f1f8b765464ec33e3066e/activerecord/lib/active_record/associations/has_many_association.rb#L32

def insert_record(record,raise = false)
    ensure_not_nested

    if record.new_record? || record.has_changes_to_save?
      if raise
        record.save!(validate: validate)
      else
        return unless record.save(validate: validate)
      end
    end

    save_through_record(record)

    record
  end

https://github.com/rails/rails/blob/5053d5251fb8c03e666f1f8b765464ec33e3066e/activerecord/lib/active_record/associations/has_many_through_association.rb#L38

如您所见,它最终会调用save方法.

免责声明:我不熟悉Rails源代码,但你有一个有趣的问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读