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

ruby-on-rails – has_many autosave_associated_records_for_ *

发布时间:2020-12-17 02:43:06 所属栏目:百科 来源:网络整理
导读:我正在尝试关联现有记录,同时仍然可以添加新记录.以下不起作用,但非常接近我的需要.如何完成关联现有记录和创建新记录? has_many :comments,:through = :commentings,:source = :commentable,:source_type = "Comment"accepts_nested_attributes_for :comme
我正在尝试关联现有记录,同时仍然可以添加新记录.以下不起作用,但非常接近我的需要.如何完成关联现有记录和创建新记录?

has_many :comments,:through => :commentings,:source => :commentable,:source_type => "Comment"
accepts_nested_attributes_for :comments,:allow_destroy => true

def autosave_associated_records_for_comments
  comments.each do |comment|
    if existing_comment = Comment.find_by_fax_and_name(comment.fax,comment.name)
      self.comments.reject! { |hl| hl.fax == existing_comment.fax && hl.name == existing_comment.name }
      self.comments << existing_comment
    else
      self.comments << comment
    end
  end
end

以下是相关的来源:https://github.com/rails/rails/blob/v3.0.11/activerecord/lib/active_record/autosave_association.rb#L155

解决方法

我已经找到了解决方案,但如果您知道更好的方法,请告诉我!

def autosave_associated_records_for_comments
  existing_comments = []
  new_comments = []

  comments.each do |comment|
    if existing_comment = Comment.find_by_fax_and_name(comment.fax,comment.name)
      existing_comments << existing_comment
    else
      new_comments << comment
    end
  end

  self.comments << new_comments + existing_comments
end

(编辑:李大同)

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

    推荐文章
      热点阅读