Unable to save custom fields after skipping post validation

(Martin Eriksson) #1

I am working on an importer script. To be able to import some weirdly formatted posts I tried passing skip_validations: true to PostCreator. This solved my problem but created a new one. It seems that the posts which are possible to create only by skipping validations do not support custom fields.

I do something like this:

post.custom_fields['my_field'] = "something"

After this I can access my_field with the expected results from the same instance, i.e. the post variable in the above example. But when I fetch the object anew from the database, the field is not there so it seems it is not actually saved. This is true only for the malformed (according to Discourse validations rules) posts, for all other posts custom fields work.

Some background:

To get on with my project I accepted the trade-off of turning validations back on and instead not importing the malformed posts. However, as it turns out I need to skip validations for another reason (to import posts into a category with restricted access), so I am back to square one with regards to the custom fields (without which my importer does not work very well, if at all).

PS. If there is a way to import to a restricted category without skipping validations, I would love to hear about it since it would help me in my current situation, but solving the custom fields problem mentioned above would be even better and I thought I should post about it anyway since I could not find any previous discussion of it or a similar issue.

(Martin Eriksson) #2

I think I figured this one out on my own, by looking around in the code for the Post model. Since the post message is still invalid, I need to do this instead:

post.custom_fields['my_field'] = "something"
post.save(validate: false)

I have tried this and it seems to work.