【问题标题】:How to accomplish an update_attributes without actually saving the changes [duplicate]如何在不实际保存更改的情况下完成 update_attributes [重复]
【发布时间】:2011-09-26 12:12:19
【问题描述】:

可能重复:
Rails update_attributes without save?

从根本上说,我想做一个 ActiveRecord“update_attributes”,同时让 ActiveRecord 更改处于待处理状态。有没有办法做到这一点?如果您想知道我为什么想要这个,请继续阅读。

我有一个由三部分组成的表单:一个静态部分(相互独立的文本字段),一组选择(随着条目的填写而增长),以及一个显示选择对一组依赖对象。更改选择需要往返服务器以确定效果,并且某些选择会影响未来选择的选择。选择被建模为基本模型的 has_many 关联。例如。 (注意 [] 条目指定 HTML-SELECT)

Include [section]
  Exclude [subsection]
  Exclude [subsection]
Include [section]
  Exclude [subsection]
...

我已将表单设置为典型的嵌套属性表单。更改选择时,我将使用Ajax发布字段,以便我收到典型的Params哈希(例如params [:baseModel] [compysign_models_attributes] [0] [:field_name])。我想把它放到一个未保存的 ActiveRecord 中,这样我已经用来生成原始页面的部分内容可以用来生成 JS 响应(我为此使用了一个 js.erb 文件)。使用 Basemodel.new(params[:basemodel]) 会报错

"ActiveRecord::RecordNotFound (Couldn't find AssociatedModel with ID=1 for Basemodel with ID=)

发生这种情况(我认为)是因为现有关联记录中的 ID(在当前记录中具有非空白 ID)与“新”调用生成的空白 ID 不匹配。

我可以做一些非常笨拙的事情并创建一些看起来像 ActiveRecord 的东西(至少足以满足我的部分),但我必须认为这是一个足够普遍的问题,因此有一个很好的解决方案。

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-3 activerecord associations update-attributes


【解决方案1】:

取决于 ActiveRecord::Persistence#update_attributes 的来源

# File activerecord/lib/active_record/persistence.rb, line 127
def update_attributes(attributes)
  # The following transaction covers any possible database side-effects of the
  # attributes assignment. For example, setting the IDs of a child collection.
  with_transaction_returning_status do
    self.attributes = attributes
    save
  end
end

您可以使用

为模型分配属性
model.attributes = attributes

其中 attributes 是模型字段等的哈希。

【讨论】:

  • 工作就像一个魅力。谢谢。下次我会在发布之前查看源代码。
【解决方案2】:

下面应该像update_attributes 一样,允许您传递模型属性的子集而不清除其他属性,以及默默地忽略散列中的任何未知属性。如果您使用字符串或符号作为哈希键,它也不应该在意。

def set_attributes (attributes)
  attributes.each do |key, value|
    self.send("#{key}=", value) if self.respond_to?("#{key}=")
  end
end

【讨论】:

  • 我认为这可能会奏效,但请参阅下一个答案以获得更优雅的解决方案。感谢您的回复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-20
  • 2020-01-21
  • 1970-01-01
  • 2014-12-10
  • 1970-01-01
  • 1970-01-01
  • 2018-03-17
相关资源
最近更新 更多