nathank
(Nathan Kershaw)
17 Febrero, 2022 21:12
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 me gusta
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 Me gusta
pfaffman
(Jay Pfaffman)
18 Febrero, 2022 10:46
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)
18 Febrero, 2022 12:19
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)
18 Febrero, 2022 18:44
6
Thank you - yes, that is what I should have used.
Yup, that is exactly what happened. I felt pretty foolish afterwards!
2 Me gusta
nathank
(Nathan Kershaw)
7 Mayo, 2022 13:09
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 Me gusta
j127
5 Agosto, 2022 02:52
8
How did you create that dynamic content in the post?
It seems that meta has this component on. (Just guessing
3 Me gusta
system
(system)
Cerrado
11 Marzo, 2023 07:42
10
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.