Manipulating custom user fields from the Rails console

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. :+1:

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

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.

By doing this, you’re replacing everything in the u.custom_fields hash with {"user_field_16" => nil}(note the nil without quotes)

Thank you - yes, that is what I should have used.

Yup, that is exactly what happened. I felt pretty foolish afterwards!

2 Likes

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

How did you create that dynamic content in the post?

It seems that meta has this component on. (Just guessing

3 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.