I have an ActiveRecord named Station
. I want to update some attributes not directly, but using a variable. Something like:
station = Station.where(attr1: "..." , attr2: "...") station.update_attributes(attr1: "...", attr2: "...", ..)
But when I initialize the station
variable I get ActiveRecord::Relation, which doesn't have the update_attributes
helper. How can i then update some fields of my Station
using a variable, but not directly ?
You should use ActiveRecord#find_by
for this goal:
station = Station.find_by(attr1: "..." , attr2: "...") # Station first instance with specified attributes
station.update_attributes(attr1: "...", attr2: "...", ..)
This method returns Station
instance if it exists with your attributes or nil
in other case.
If you want find all Station
instances and update each, you should use ActiveRecord#update_all
method:
stations = Station.where(attr1: "..." , attr2: "...") #ActiveRecord::Relation
stations.update_all(attr1: "new_attr1" , attr2: "new_attr_2")
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments