In some cases, one may not want to save attributes retrieved from a form
to the database right away. Would the best way to bulk update your AR
object from the params hash be to do:
For some reason, I was under the impression that update_attributes
didn’t update the record in the database and so now I’m trying to find
the appropriate replacement.
@ar_obj = ArObj.new(params[:id])
if @ar_obj.valid?
whatever code you need here for good objects
@ar_obj.save
else
whatever code you have for erroneous information
end
AR is smart enough to figure out whether a record already exists by
primary
key, so save will INSERT if it’s a new record or UPDATE if it’s an
existing
one. Updating attributes skips straight to the database before giving
you a
look. That’s why creating from the params has is so powerful.
So what if you don’t have a params hash? Make one:
In some cases, one may not want to save attributes retrieved from a form
to the database right away. Would the best way to bulk update your AR
object from the params hash be to do:
attributes, but merge! will preserve them.
No, the attributes= method does not assign a new attribute hash.
It just assigns new values to the attributes (and attr_accessors)
keyed in the RHS hash.
–
We develop, watch us RoR, in numbers too big to ignore.
is all you need. The only attributes set are those named
by keys in the params hash.
Shouldn’t you merge the keys, given the possibility that your object may
have an unsaved attribute set already (that you want to keep) that is
not represented in your params hash. Using = will blow away those
attributes, but merge! will preserve them.
OK I’m convinced. I had tested using “=” instead of merge! and I had
convinced myself that “=” would blow away keys. But I just retested it
and it works as described. I must have made a mistake on the first
test.
Interestingly (well, maybe not…) enough, I was attempting to use
merge! and I could not get it to work to copy a params hash into an
attribute hash, even though I verified the existence of the same keys
(of the same “type”) in the two hashes, and I was able to copy the
values across fine if I used an interator on the params hash.
I recalled that the params hash is a HashWithIndifferentAccess and the
attributes Hash is a regular Hash - maybe that has something to do with
it. Weird.
Wes
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.