Rails控制器:@ foo.update定义在哪里?

时间:2016-06-17 00:31:54

标签: ruby-on-rails activerecord

尝试追踪an issue更新记录,并进入此块:

# PATCH/PUT /artefacts/1
# PATCH/PUT /artefacts/1.json
def update
  respond_to do |format|
    if @artefact.update(artefact_params)
      format.html { redirect_to @artefact, notice: 'Artefact was successfully updated.' }
      format.json { render :show, status: :ok, location: @artefact }
    else
      format.html { render :edit }
      format.json { render json: @artefact.errors, status: :unprocessable_entity }
    end
  end
end

现在,对我来说,这似乎是update的定义正在检查自己,但这不是正确的,因为没有代码可以解析artefact_params

我错过了什么?解析params并保存记录的代码在哪里?

(使用Rails 5.0rc1)

1 个答案:

答案 0 :(得分:1)

您可以在rails/activerecord/lib/active_record/persistence.rb文件中找到您所关注的代码。

以下是相关代码:

# Updates the attributes of the model from the passed-in hash and saves the
# record, all wrapped in a transaction. If the object is invalid, the saving
# will fail and false will be returned.
def update(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
    assign_attributes(attributes)
    save
  end
end

来自rails/activemodel/lib/active_model/attribute_assignment.rb

def assign_attributes(new_attributes)
  if !new_attributes.respond_to?(:stringify_keys)
    raise ArgumentError, "When assigning attributes, you must pass a hash as an argument."
  end
  return if new_attributes.nil? || new_attributes.empty?

  attributes = new_attributes.stringify_keys
  _assign_attributes(sanitize_for_mass_assignment(attributes))
end

private

def _assign_attributes(attributes)
  attributes.each do |k, v|
    _assign_attribute(k, v)
  end
end

def _assign_attribute(k, v)
  if respond_to?("#{k}=")
    public_send("#{k}=", v)
  else
    raise UnknownAttributeError.new(self, k)
  end
end