【问题标题】:Postgresql & Rails 3 - Update_attribute on elements in an array reorders the array..why?Postgresql & Rails 3 - 数组中元素的 Update_attribute 重新排序数组..为什么?
【发布时间】:2011-05-18 03:55:23
【问题描述】:

Postgresql / Rails 3 / Ruby 1.9.2 / OSX

class Deliverable < ActiveRecord::Base
  has_many :models, :dependent => :destroy

  def build_template
    models << sect_letterhead << sect_ica << sect_project_description_exhibit
  end

end



ruby-1.9.2-p180 :002 > d.models.first
 => #<Model id: 1, company_id: nil, deliverable_id: 1, model_id: nil, type: nil, kind: "cover_page", csv_file_name: nil, csv_content_type: nil, csv_file_size: nil, csv_updated_at: nil> 

ruby-1.9.2-p180 :003 > d.models.first.update_attribute(:csv_file_name, "blah")
 => true 

ruby-1.9.2-p180 :004 > d.models.first
 => #<Model id: 5, company_id: nil, deliverable_id: 1, model_id: nil, type: nil, kind: "opening_letter", csv_file_name: nil, csv_content_type: nil, csv_file_size: nil, csv_updated_at: nil> 

每当我 update_attribute 一个模型时,该模型都会被推到数组的末尾。 除了分配一个自定义排序属性来避免在调用 update_attribute 时更改数组顺序之外,还有其他方法吗?我可以很容易地做到这一点,但我对数据库的行为很感兴趣。

即使我从模型对象中删除时间戳,行为仍然存在。

如果没有时间戳来跟踪刚刚更新的模型,这将如何发生?或者当我调用update_attribute时,模型实际上是从数组中拉出并放回最后一个位置吗?

【问题讨论】:

  • 将“default_scope order('id')”添加到 model.rb 解决了这个问题,但我仍然不明白为什么默认值是在看似幻影的 updated_at 上
  • 更新属性后试试d.models.first.save

标签: ruby-on-rails arrays ruby-on-rails-3 postgresql


【解决方案1】:

我不是 PostgreSQL 专家,但我注意到了同样的行为。我的理解是 PostgreSQL 本身没有默认顺序(而 MySQL 是可靠的——据我所知——按主键排序)。 PostgreSQL的数据格式可能意味着修改后的记录会移到最后。

简而言之:这不是 Rails 的东西 - 它是 PostgreSQL 的东西,因此时间戳无关紧要。

无论哪种方式,它都会迫使您清楚要退回物品的顺序。这不是一个糟糕的主意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    相关资源
    最近更新 更多