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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – rails – 左移“<<”运算符自动保存记录前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
需要帮助理解这段代码,据我所知,我知道“<<”附加到集合但在这里它正确保存记录,如果不调用.save方法怎么办?
  1. #user.rb
  2. has_many :saved_properties,through: :property_saves,source: :property
  3.  
  4. #users_controller.rb
  5. def update
  6. if @user.saved_properties << Property.find(params[:saved_property_id])
  7. render plain: "Property saved"
  8. end

解决方法

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

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

  1. def concat(*records)
  2. records = records.flatten
  3. if owner.new_record?
  4. load_target
  5. concat_records(records)
  6. else
  7. transaction { concat_records(records) }
  8. end
  9. end

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

  1. def concat_records(records,should_raise = false)
  2. result = true
  3.  
  4. records.each do |record|
  5. raise_on_type_mismatch!(record)
  6. add_to_target(record) do |rec|
  7. result &&= insert_record(rec,true,should_raise) unless owner.new_record?
  8. end
  9. end
  10.  
  11. result && records
  12. end

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

  1. def insert_record(record,validate = true,raise = false)
  2. set_owner_attributes(record)
  3. set_inverse_instance(record)
  4.  
  5. if raise
  6. record.save!(validate: validate)
  7. else
  8. record.save(validate: validate)
  9. end
  10. end

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

  1. def insert_record(record,raise = false)
  2. ensure_not_nested
  3.  
  4. if record.new_record? || record.has_changes_to_save?
  5. if raise
  6. record.save!(validate: validate)
  7. else
  8. return unless record.save(validate: validate)
  9. end
  10. end
  11.  
  12. save_through_record(record)
  13.  
  14. record
  15. end

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

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

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

猜你在找的Ruby相关文章