如何获取key/val对的散列并用它设置ActiveRecord属性



我有一个Ruby哈希,我正在通过远程web API检索。我有一个ActiveRecord模型,它具有与哈希中的键相同的属性。RubyonRails 4有没有一种简单的方法可以将hash中的key/val对分配给模型实例?是否可以忽略不存在的密钥?

超级简单!

更新属性而不保存:

model.attributes = your_hash
# in spite of resembling an assignemnt, it just sets the given attributes

保存更新属性:

model.update_attributes(your_hash)
# if it fails because of validation, the attributes are update in your object
# but not in the database

如果无法保存,则更新属性、保存和提升

model.update_attributes!(your_hash)

根据Rails文档:

更新(属性)

根据传入的哈希更新模型的属性并保存记录,所有这些都封装在事务中。如果对象无效,则保存将失败,并返回false

所以试试

model.update(dat_hash) #dat_hash being the hash with the attributes

我在Rails3.2中使用update_attributes做了同样的事情,这是同样的事情。这是我的代码:

def update
  @form = get_form(params[:id])
  @form.update_attributes(params[:form])
  @form.save
  if @form.save
    render json: @form
  else
    render json: @form.errors.full_messages, status: :unprocessable_entity
  end
end

它只更新哈希中的属性。

最新更新