0

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

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"}}})

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

页面.rb

class Page < ActiveRecord::Base
  has_many :paragraphs, :dependent => :destroy
  attr_accessible :name, :paragraphs_attributes
  accepts_nested_attributes_for :paragraphs, :allow_destroy => true
end

段落.rb

class Paragraph < ActiveRecord::Base
  belongs_to :page
  attr_accessible :title, :body, :page, :date
  validates :page,  presence: true
end

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

4

2 回答 2

0

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

检查语法

   # 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
于 2014-11-13T01:26:30.510 回答
0

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

page_controller.rb

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
于 2013-01-02T10:09:46.103 回答