首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在某些情况下,update_attributes不会更新nested_attributes

在某些情况下,update_attributes不会更新nested_attributes
EN

Stack Overflow用户
提问于 2013-01-02 06:32:11
回答 2查看 519关注 0票数 0

我正在用rails 3.2.8编写一个小的CMS应用程序。有一个针对段落(基本上保存新闻文章的标题、正文和日期)和页面(由许多段落组成,例如许多新闻文章)的模型。以下代码仅在日期更改时更新段落,否则,即使正文更改,段落也不会更新!?

代码语言:javascript
复制
page.update_attributes({"paragraphs_attributes"=>{"0"=>{"_destroy"=>"0", 
             "title"=>"News title", "body"=>"News text", "id"=>"4", 
             "date(3i)"=>"1", "date(2i)"=>"1", "date(1i)"=>"2013"}}})

下面,您可以找到模型的相关部分:

page.rb

代码语言:javascript
复制
class Page < ActiveRecord::Base
  has_many :paragraphs, :dependent => :destroy
  attr_accessible :name, :paragraphs_attributes
  accepts_nested_attributes_for :paragraphs, :allow_destroy => true
end

paragraph.rb

代码语言:javascript
复制
class Paragraph < ActiveRecord::Base
  belongs_to :page
  attr_accessible :title, :body, :page, :date
  validates :page,  presence: true
end

有谁知道这种奇怪行为的原因吗?

EN

回答 2

Stack Overflow用户

发布于 2013-01-02 18:09:46

当然,也有可能出现肮脏的变通方法:在最终更新之前插入一个假更新。请注意,这是非常糟糕的风格,并且使更新的数据库访问加倍,但由于我找不到其他解决方案,我提出了以下解决方案:

page_controller.rb

代码语言:javascript
复制
class PageController < ApplicationController

  def update

    # Hack: Updating paragraphs fails for some strange reasons if their date 
    # did not change. Updating paragraphs with date changes works as expected.
    # To allow updates in all cases, we first make an update to an impossible
    # date and then make an update to the real date.


    # Define a year, that will never occure in the params.
    # This date will be used for the fake update.
    impossible_year = "1999"

    # Setup the fake params for the first fake update (Change the date fields of 
    # all paragraphs to an impossible date).
    fake_params = params[:page].deep_dup
    par_attrs = fake_params[:paragraphs_attributes]
    par_attrs.keys.each do |key|
      par_attrs[key]["date(1i)"] = impossible_year
    end

    # Perform the fake update.
    @page.update_attributes(fake_params)

    # Finally do the real update with the original params.
    @page.update_attributes(params[:page])
  end
end
票数 0
EN

Stack Overflow用户

发布于 2014-11-13 09:26:31

https://github.com/rails/rails/blob/d32965399ccfa2052a4d52b70db1bae0ca16830b/activerecord/lib/active_record/nested_attributes.rb#L72

检查语法

代码语言:javascript
复制
   # Now, when you add the <tt>_delete</tt> key to the attributes hash, with a
    # value that evaluates to +true+, you will destroy the associated model:
    #
    #   member.avatar_attributes = { :id => '2', :_delete => '1' }
    #   member.avatar.marked_for_destruction? # => true
    #   member.save
    #   member.avatar #=> nil
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14114849

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档