randombits
randombits

Reputation: 48490

How to take a hash of key/val pairs and set ActiveRecord attributes with it

I have a Ruby hash that I'm retrieving via a remote web API. I have an ActiveRecord model that has the same attributes as the keys in the hash. Is there a trivial way with Ruby on Rails 4 to assign the key/val pairs from the hash to the model instance? Is it possible to ignore the keys that do not exist?

Upvotes: 4

Views: 4938

Answers (2)

rewritten
rewritten

Reputation: 16435

Super-easy!

Update the attributes without saving:

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

Update attributes saving:

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

Update attributes, save, and raise if unable to save

model.update_attributes!(your_hash)

Upvotes: 5

RustyToms
RustyToms

Reputation: 7820

According to the Rails docs:

update(attributes)

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.

So try

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

I have been doing the same thing in Rails 3.2 using update_attributes, which is the same thing. Here is my code:

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

It only updates the attributes that are in the hash.

Upvotes: 3

Related Questions