我正在用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"}}})下面,您可以找到模型的相关部分:
page.rb
class Page < ActiveRecord::Base
has_many :paragraphs, :dependent => :destroy
attr_accessible :name, :paragraphs_attributes
accepts_nested_attributes_for :paragraphs, :allow_destroy => true
endparagraph.rb
class Paragraph < ActiveRecord::Base
belongs_to :page
attr_accessible :title, :body, :page, :date
validates :page, presence: true
end有谁知道这种奇怪行为的原因吗?
发布于 2013-01-02 18:09:46
当然,也有可能出现肮脏的变通方法:在最终更新之前插入一个假更新。请注意,这是非常糟糕的风格,并且使更新的数据库访问加倍,但由于我找不到其他解决方案,我提出了以下解决方案:
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发布于 2014-11-13 09:26:31
检查语法
# 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 #=> nilhttps://stackoverflow.com/questions/14114849
复制相似问题