2

I have a hash like so:

{
 "feid"=>32, 
 "fid"=>11, 
 "fipl"=>11, 
}

I want to save each value to it's respective column in a database.

I know I can do the following

    record = Metric.new
    record.feid = hash['feid']
    record.fid  = hash['fid']
    record.fipl = hash['fipl']
    record.save

But my hash is a lot longer than 3 elements and there must be much more simple way!

1
  • Do record.update_attributes(hash)... if record already exists, Commented Mar 4, 2014 at 10:48

1 Answer 1

4

There is. For new record (creation, assignment and saving to db in one go):

record = Metric.create(hash)

Creation and assignment without saving:

record = Metric.new(hash)

For existing record, assigning and saving:

record.update_attributes(hash)

and assignnment without saving:

record.assign_attributes(hash)

Note:

Saving methods (create and update) will not raise an exception if saving fails (e.g because of failing validation). Saving fails quietly. If you want to get an exception when this happens, use banged versions: create! and update_attributes!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, I tried record = Metric.new(hash) but I wondered why it wasn't inserting into the db. I understand why now :p
Just as a little extra comment, as well as obj.assign_attributes(hash) you can do obj.attributes = hash: the two are equivalent but the latter may be syntactically preferable in some contexts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.