質問

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!

役に立ちましたか?

解決

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!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top