跳到內文 跳到搜尋
方法
B
C
I
Q
U

執行個體公用方法

build(attributes = nil, &block)

建立物件 (或多個物件),並回傳建立的物件或建立的物件清單。

attributes 參數可以是 雜湊 或包含雜湊的 陣列。這些雜湊描述物件的屬性,準備好要建立。

範例

# Build a single new object
User.build(first_name: 'Jamie')

# Build an Array of new objects
User.build([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }])

# Build a single object and pass it into a block to set other attributes.
User.build(first_name: 'Jamie') do |u|
  u.is_admin = false
end

# Building an Array of new objects using a block, where the block is executed for each object:
User.build([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }]) do |u|
  u.is_admin = false
end
# File activerecord/lib/active_record/persistence.rb, line 82
def build(attributes = nil, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| build(attr, &block) }
  else
    new(attributes, &block)
  end
end

create(attributes = nil, &block)

建立物件 (或多個物件),在驗證通過的情況下儲存到資料庫中。無關於物件是否成功儲存到資料庫中,都會回傳生成的物件。

attributes 參數可以是 雜湊 或包含雜湊的 陣列。這些雜湊描述要建立的物件屬性。

範例

# Create a single new object
User.create(first_name: 'Jamie')

# Create an Array of new objects
User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }])

# Create a single object and pass it into a block to set other attributes.
User.create(first_name: 'Jamie') do |u|
  u.is_admin = false
end

# Creating an Array of new objects using a block, where the block is executed for each object:
User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }]) do |u|
  u.is_admin = false
end
# File activerecord/lib/active_record/persistence.rb, line 33
def create(attributes = nil, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| create(attr, &block) }
  else
    object = new(attributes, &block)
    object.save
    object
  end
end

create!(attributes = nil, &block)

建立物件 (或多個物件),在驗證通過的情況下儲存到資料庫中。如果驗證失敗,會引發 RecordInvalid 錯誤,與 Base#create 不同。

attributes 參數可以是 雜湊 或包含雜湊的 陣列。這些屬性描述要建立在單一物件或多個物件 (如果提供雜湊陣列) 上的屬性。

# File activerecord/lib/active_record/persistence.rb, line 50
def create!(attributes = nil, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| create!(attr, &block) }
  else
    object = new(attributes, &block)
    object.save!
    object
  end
end

instantiate(attributes, column_types = {}, &block)

根據屬性雜湊,instantiate 會回傳合適類別的新執行個體。僅接受字串作為金鑰。

例如,Post.all 可能透過在 type 屬性中儲存記錄的子類別,來回傳留言、訊息和電子郵件。透過呼叫 instantiate (而不是 new),尋找方法能確保為每筆記錄取得合適類別的新執行個體。

請參閱 ActiveRecord::Inheritance#discriminate_class_for_record 來了解如何實作此「單一表格」繼承對應。

# File activerecord/lib/active_record/persistence.rb, line 100
def instantiate(attributes, column_types = {}, &block)
  klass = discriminate_class_for_record(attributes)
  instantiate_instance_of(klass, attributes, column_types, &block)
end

query_constraints(*columns_list)

接受要在 SELECT / UPDATE / DELETE 查詢的 WHERE 子句和 `#first` 及 `#last` 檢索器方法的 ORDER BY 子句中使用的屬性名稱清單。

class Developer < ActiveRecord::Base
  query_constraints :company_id, :id
end

developer = Developer.first
# SELECT "developers".* FROM "developers" ORDER BY "developers"."company_id" ASC, "developers"."id" ASC LIMIT 1
developer.inspect # => #<Developer id: 1, company_id: 1, ...>

developer.update!(name: "Nikita")
# UPDATE "developers" SET "name" = 'Nikita' WHERE "developers"."company_id" = 1 AND "developers"."id" = 1

# It is possible to update an attribute used in the query_constraints clause:
developer.update!(company_id: 2)
# UPDATE "developers" SET "company_id" = 2 WHERE "developers"."company_id" = 1 AND "developers"."id" = 1

developer.name = "Bob"
developer.save!
# UPDATE "developers" SET "name" = 'Bob' WHERE "developers"."company_id" = 1 AND "developers"."id" = 1

developer.destroy!
# DELETE FROM "developers" WHERE "developers"."company_id" = 1 AND "developers"."id" = 1

developer.delete
# DELETE FROM "developers" WHERE "developers"."company_id" = 1 AND "developers"."id" = 1

developer.reload
# SELECT "developers".* FROM "developers" WHERE "developers"."company_id" = 1 AND "developers"."id" = 1 LIMIT 1
# File activerecord/lib/active_record/persistence.rb, line 212
def query_constraints(*columns_list)
  raise ArgumentError, "You must specify at least one column to be used in querying" if columns_list.empty?

  @query_constraints_list = columns_list.map(&:to_s)
  @has_query_constraints = @query_constraints_list
end

update(id = :all, attributes)

更新物件(或多個物件)並將其儲存至資料庫中(如果驗證通過)。會傳回產生的物件,無論是否已將該物件成功儲存至資料庫中。

參數

  • id - 應該是待更新的 id 或 id 陣列。選用參數,預設為關係中的所有記錄。

  • attributes - 應該是屬性雜湊或雜湊陣列。

範例

# Updates one record
Person.update(15, user_name: "Samuel", group: "expert")

# Updates multiple records
people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
Person.update(people.keys, people.values)

# Updates multiple records from the result of a relation
people = Person.where(group: "expert")
people.update(group: "masters")

注意:更新大量的記錄會為每個記錄執行一項 UPDATE 查詢,這可能會造成效能問題。如果不需要為每個記錄更新執行回呼,則最好使用 update_all 針對一項查詢更新所有記錄。

# File activerecord/lib/active_record/persistence.rb, line 132
def update(id = :all, attributes)
  if id.is_a?(Array)
    if id.any?(ActiveRecord::Base)
      raise ArgumentError,
        "You are passing an array of ActiveRecord::Base instances to `update`. " \
        "Please pass the ids of the objects by calling `pluck(:id)` or `map(&:id)`."
    end
    id.map { |one_id| find(one_id) }.each_with_index { |object, idx|
      object.update(attributes[idx])
    }
  elsif id == :all
    all.each { |record| record.update(attributes) }
  else
    if ActiveRecord::Base === id
      raise ArgumentError,
        "You are passing an instance of ActiveRecord::Base to `update`. " \
        "Please pass the id of the object by calling `.id`."
    end
    object = find(id)
    object.update(attributes)
    object
  end
end

update!(id = :all, attributes)

更新物件(或多個物件),就像使用 update 一樣,但會呼叫 update!,而不是 update,所以如果記錄無效且儲存會失敗,就會引發例外狀況。

# File activerecord/lib/active_record/persistence.rb, line 158
def update!(id = :all, attributes)
  if id.is_a?(Array)
    if id.any?(ActiveRecord::Base)
      raise ArgumentError,
        "You are passing an array of ActiveRecord::Base instances to `update!`. " \
        "Please pass the ids of the objects by calling `pluck(:id)` or `map(&:id)`."
    end
    id.map { |one_id| find(one_id) }.each_with_index { |object, idx|
      object.update!(attributes[idx])
    }
  elsif id == :all
    all.each { |record| record.update!(attributes) }
  else
    if ActiveRecord::Base === id
      raise ArgumentError,
        "You are passing an instance of ActiveRecord::Base to `update!`. " \
        "Please pass the id of the object by calling `.id`."
    end
    object = find(id)
    object.update!(attributes)
    object
  end
end