nathank
(Nathan Kershaw)
February 17, 2022, 9:12pm
1
I used this code snipped to attempt to bulk replace some data in a user custom field. I derived it from the Ning importer .
users=User.where("users.created_at <= '2019-09-13'::timestamp")
users.each do |u|
u.custom_fields = {"user_field_16" => "Nil"}
u.save
end
However it had the unintended consequence of wiping the users’ other custom field values.
Can anyone suggest a way to modify a user custom field value from the console that doesn’t cause chaos?
1 Like
I think this format changes only the custom field in question. I’ve tested it briefly, and it seemed to do the trick.
users=User.where("users.created_at <= '2019-09-13'::timestamp")
users.each do |u|
u.custom_fields["user_field_16"] = "Nil"
u.save
end
Though if you wanted the field to be NULL rather than say ‘Nil’ you could try this instead:
users=User.where("users.created_at <= '2019-09-13'::timestamp")
users.each do |u|
u.custom_fields["user_field_16"] = NIL
u.save
end
4 Likes
pfaffman
(Jay Pfaffman)
February 18, 2022, 10:46am
3
Also something like
UserCustomField.create(user_id: 1, name: "user_field_4",value: "Oops")
Oh, but if that already has a value, it’ll add a second one! So you might
ucf=UserCustomField.find_by(user_id: name: 'user_field_4')
and then you’d need to either update it or create a new one.
But if you do create multiple ones, the UX will show them comma-separated, and if they are edited via the UX when they get saved, they get saved back to a single value.
You can have a look at them with
UserCustomField.all
Or
UserCustomField.where(name: x)
That’s by memory on my phone so your mileage may vary.
fzngagan
(Faizaan Gagan)
February 18, 2022, 12:19pm
5
By doing this, you’re replacing everything in the u.custom_fields
hash with {"user_field_16" => nil}
(note the nil without quotes)
nathank
(Nathan Kershaw)
February 18, 2022, 6:44pm
6
Thank you - yes, that is what I should have used.
Yup, that is exactly what happened. I felt pretty foolish afterwards!
2 Likes
nathank
(Nathan Kershaw)
May 7, 2022, 1:09pm
7
I find this a useful tool for getting the rails syntax right when you want to manipulate these UCFs in the Rails console:
If you are replacing data in that field
UserCustomField.find_by(user_id: =UserID=, name: "=UserFieldName=").update(value: "=NewValue=")
(will give you an error if there isn’t any data in that field yet)
If you are filling that field for the first time
UserCustomField.create(user_id: =UserID=, name: "=UserFieldName=",value: "=NewValue=")
7 Likes
j127
August 5, 2022, 2:52am
8
How did you create that dynamic content in the post?
Kuro22
August 5, 2022, 3:01am
9
It seems that meta has this component on. (Just guessing
3 Likes
system
(system)
Closed
March 11, 2023, 7:42am
10
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.