Adding an arbitrary custom_field with a specified type to a plugin

Hi @joebuhlig. I hope to make a plugin that extends what types of attributes models, like Topic, have, and I noticed you have a reasonable custom_field called vote_count added to the Topic model…

I’m familiar with Rails and expected a migration or a least a type declaration for vote_count somewhere (I did search the repo for vote_count, and only saw it in code/templating). Moreover, all the discussion on Discourse meta pertains to custom_fields for Users, not really custom_fields in general. Is there a how-to guide on adding an arbitrary custom_field with a specified type to a plugin that you might point me to?

That’s not exactly an arbitrary custom field. It’s a custom field on the Topic. You can do the same for a Category and User. I can’t say that I remember seeing any docs on it. I simply saw the ability when running through the master codebase. That’s how I determine most of the possibilities. It would be tough for the team to manage that level of documentation on something moving so fast.

That said, if you look through the Topic model extension I did, you can see the use of custom fields on all three.

https://github.com/discourse/discourse-feature-voting/blob/master/plugin.rb#L209

1 Like

@joebuhlig thank you for clarifying your M.O…I just have one quick last question.

I’m still a little confused as to how a custom_field's type gets set in the database. In this plugin, I clearly see where the typing is set, with register_custom_field_type(). Why does your plugin and a few others I’ve looked at not have to use this particular method?

The custom_field spec tests make it apparent that its flexible for typing, but I guess both ways are just fine.
https://github.com/discourse/discourse/blob/5dbd6a304bed5400be481d71061d3e3ebb4d6785/spec/components/concern/has_custom_fields_spec.rb

1 Like

And that’s how I would discover it as well. :wink: