# Che cos'è questa funzione add\_to\_serializer in tutti questi plugin

**URL:** https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913
**Category:** Development
**Created:** [12 Marzo 2017, 5:07am UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913 "2017-03-12T05:07:15Z")
**Posts on this page:** 20
**Page:** 1

<div class="post-metadata">

### Author: ![net\_deamon](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/net_deamon/32/70126_2.png) [@net\_deamon](https://meta.discourse.org/u/net_deamon)
#### Post date: [12 Marzo 2017, 5:07am UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/1 "2017-03-12T05:07:15Z")

</div>

I have seen this code in [discourse\_signatures plugin](https://github.com/xfalcox/discourse-signatures/blob/master/plugin.rb#L20)

```rb
User.register_custom_field_type('see_signatures', :boolean)
User.register_custom_field_type('signature_url', :text)
User.register_custom_field_type('signature_raw', :text)

if SiteSetting.signatures_enabled then
  add_to_serializer(:post, :user_signature, false) {
    if SiteSetting.signatures_advanced_mode then
      object.user.custom_fields['signature_raw']
    else
      object.user.custom_fields['signature_url']
    end
  }

  # I guess this should be the default @ discourse. PR maybe?
  add_to_serializer(:user, :custom_fields, false) {
    if object.custom_fields == nil then
      {}
    else
      object.custom_fields
    end
  }
end

```

In [discourse national flags plugin](https://github.com/Ebsy/discourse-nationalflags/blob/master/plugin.rb#L27)

```rb
User.register_custom_field_type('nationalflag_iso', :text)

if SiteSetting.nationalflag_enabled then
  byebug;
  add_to_serializer(:post, :user_signature, false) {
    object.user.custom_fields['nationalflag_iso']
  }
  byebug;
  # I guess this should be the default @ discourse. PR maybe?
  add_to_serializer(:user, :custom_fields, false) {
    if object.custom_fields == nil then
      {}
    else
      object.custom_fields
    end
  }
end

```

I am not able to understand what is `add_to_serializer` is doing.

**I checked in def add\_to\_serializer**

```rb
def add_to_serializer(serializer, attr, define_include_method=true, &block)
  klass = "#{serializer.to_s.classify}Serializer".constantize rescue "#{serializer.to_s}Serializer".constantize

  klass.attributes(attr) unless attr.to_s.start_with?("include_")

  klass.send(:define_method, attr, &block)

  return unless define_include_method

  # Don't include serialized methods if the plugin is disabled
  plugin = self
  klass.send(:define_method, "include_#{attr}?") { plugin.enabled? }
end

```

I understand that `User.register_custom_field_type('signature_raw', :text)` will register a custom field type to `User` object. But what is `add_to_serializer` doing? I am not able to understand, can you explain me in plain english?

---

<div class="post-metadata">

### Author: ![gdpelican](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/gdpelican/32/81308_2.png) [@gdpelican](https://meta.discourse.org/u/gdpelican)
#### Post date: [12 Marzo 2017, 5:50am UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/2 "2017-03-12T05:50:30Z")

</div>

It’s essentially adding to the information that Discourse serializes out when sending that model to the client. For example, you may see a request to this endpoint when loading up a topic page:

```plaintext
http://meta.discourse.org/t/2349082394.json

```

which returns some payload like this:

```json
{
  title: "Some topic title",
  archetype: 'regular',
  category_id: 7,
  post_stream: { posts: [...] },
  posts_count: 15,
  (etc etc.. lots more info about the topic in question)
}

```

Which is the json representation of a Discourse topic.

If I want to know more about the topic because of additional ‘stuff’ I do in my plugin, I can put in a line like

```rb
add_to_serializer :topic, :flag_name do
  object.flag_name # <- NB that 'object' here is the topic being serialized
end

```

(Also, by default, this method simply sends the specified message to ‘object’, meaning that

```rb
add_to_serializer :topic, :flag_name

```

is the same as

```rb
add_to_serializer :topic, :flag_name do
  object.flag_name
end

```

)

Once I’ve added the method to the serializer, I can end up with JSON output which includes that additional info

```json
{
  title: "Some topic title",
  archetype: 'regular',
  category_id: 7,
  post_stream: { posts: [...] },
  posts_count: 15,
  flag_name: "some flag name"
  ...
}

```

Also note that you could achieve the same thing by overwriting the TopicSerializer class (which is exactly what the code snippet you’ve provided is doing)

```rb
# plugin.rb
TopicSerializer.class_eval do
  attributes :flag_name
  def flag_name
    object.flag_name
  end
end

```

---

<div class="post-metadata">

### Author: ![net\_deamon](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/net_deamon/32/70126_2.png) [@net\_deamon](https://meta.discourse.org/u/net_deamon)
#### Post date: [15 Marzo 2017, 4:18pm UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/4 "2017-03-15T16:18:52Z")

</div>

Hi,  
When running the following code,

```
TopicSerializer.class_eval do
  attributes :flag_name
  def flag_name
    object.flag_name
  end
end

```

I was getting the error “block in activate!': uninitialized constant TopicSerializer (NameError)”. I think I have to “import” or “require” the TopicSerializer dependency. Can you please tell me what would be the dependency, as I am not able to figure it out.

---

<div class="post-metadata">

### Author: ![joebuhlig](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/joebuhlig/32/193054_2.png) [@joebuhlig](https://meta.discourse.org/u/joebuhlig)
#### Post date: [15 Marzo 2017, 4:36pm UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/5 "2017-03-15T16:36:25Z")

</div>

Add this directly above your code `require_dependency 'topic_serializer'`

```ruby
require_dependency 'topic_serializer'
class ::TopicSerializer
  attributes :flag_name
  def flag_name
    object.flag_name
  end
end

```

---

<div class="post-metadata">

### Author: ![net\_deamon](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/net_deamon/32/70126_2.png) [@net\_deamon](https://meta.discourse.org/u/net_deamon)
#### Post date: [15 Marzo 2017, 4:42pm UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/6 "2017-03-15T16:42:32Z")

</div>

Hi thanks, but I got the error " `load’: No such file to load – topic\_serializer (LoadError)". Does it pull from the app/serializers folder? I checked in that folder, I could find topic\_list\_serializer.rb, and many other related to topic, but couldnt find topic\_serializer.rb

---

<div class="post-metadata">

### Author: ![joebuhlig](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/joebuhlig/32/193054_2.png) [@joebuhlig](https://meta.discourse.org/u/joebuhlig)
#### Post date: [15 Marzo 2017, 4:48pm UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/7 "2017-03-15T16:48:49Z")

</div>

Right! Try `TopicViewSerializer`.

```ruby
require_dependency 'topic_view_serializer'
class ::TopicViewSerializer
  attributes :flag_name
  def flag_name
    object.flag_name
  end
end

```

---

<div class="post-metadata">

### Author: ![fzngagan](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/fzngagan/32/259349_2.png) [@fzngagan](https://meta.discourse.org/u/fzngagan)
#### Post date: [3 Agosto 2019, 5:20pm UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/8 "2019-08-03T17:20:02Z")

</div>

Ehi, ho aggiunto un campo personalizzato alla casella di modifica della categoria.

Quando invio il modulo, vedo che questi campi vengono inviati nella console JS:  
`custom_fields[default_tag][]:good-feedback custom_fields[default_tag][]:one-more-tag`

Nel mio file principale del plugin, sto facendo:

add\_to\_serializer(:basic\_category, :default\_tag){object.custom\_fields[“default\_tag”]}

I miei campi personalizzati non vengono salvati nel database.

---

<div class="post-metadata">

### Author: ![merefield](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/merefield/32/176214_2.png) [@merefield](https://meta.discourse.org/u/merefield)
#### Post date: [22 Agosto 2019, 9:47am UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/9 "2019-08-22T09:47:18Z")

</div>

> [@fzngagan](#):
>
> nel mio file del plugin principale, sto facendo
> 
> add\_to\_serializer(:basic\_category, :default\_tag){object.custom\_fields[“default\_tag”]}
> 
> I miei campi personalizzati non vengono salvati nel database.

funziona ora se si fa:

```plaintext
add_to_serializer(:basic_category, :default_tag, false ){object.custom_fields["default_tag"]}

```

---

<div class="post-metadata">

### Author: ![fzngagan](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/fzngagan/32/259349_2.png) [@fzngagan](https://meta.discourse.org/u/fzngagan)
#### Post date: [22 Agosto 2019, 9:52am UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/11 "2019-08-22T09:52:33Z")

</div>

L’avevo risolto in quel momento aggiungendo una funzione all’evento `:before_action` e convertendo l’array in una stringa delimitata e viceversa durante il recupero.

Non ho approfondito il motivo per cui un array non può essere memorizzato come campo personalizzato senza configurazioni aggiuntive.

---

<div class="post-metadata">

### Author: ![merefield](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/merefield/32/176214_2.png) [@merefield](https://meta.discourse.org/u/merefield)
#### Post date: [22 Agosto 2019, 9:53am UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/12 "2019-08-22T09:53:32Z")

</div>

Quindi questo potrebbe potenzialmente snellire il codice?

---

<div class="post-metadata">

### Author: ![fzngagan](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/fzngagan/32/259349_2.png) [@fzngagan](https://meta.discourse.org/u/fzngagan)
#### Post date: [22 Agosto 2019, 9:54am UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/13 "2019-08-22T09:54:21Z")

</div>

Sì, funzionerebbe se funzionasse in questo caso. Ci proverò tra un po’ e ti farò sapere.

---

<div class="post-metadata">

### Author: ![merefield](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/merefield/32/176214_2.png) [@merefield](https://meta.discourse.org/u/merefield)
#### Post date: [22 Agosto 2019, 9:56am UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/14 "2019-08-22T09:56:51Z")

</div>

Povero te, dev’essere stato doloroso in quel momento 😉

---

<div class="post-metadata">

### Author: ![fzngagan](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/fzngagan/32/259349_2.png) [@fzngagan](https://meta.discourse.org/u/fzngagan)
#### Post date: [22 Agosto 2019, 10:00am UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/15 "2019-08-22T10:00:40Z")

</div>

Era una domenica sera e la curiosità ha preso il sopravvento. È stato un po’ doloroso ma divertente.  
Era qualcosa che @pfaffman stava cercando di fare.

> [@merefield](#):
>
> Povero te, deve essere stato doloroso all’epoca 😉

Niente dolore, niente guadagno 😉

---

<div class="post-metadata">

### Author: ![merefield](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/merefield/32/176214_2.png) [@merefield](https://meta.discourse.org/u/merefield)
#### Post date: [22 Agosto 2019, 10:03am UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/16 "2019-08-22T10:03:19Z")

</div>

> [@fzngagan](#):
>
> Niente dolore, niente guadagno 😉

haha, è proprio vero! …

---

<div class="post-metadata">

### Author: ![Cyrine](https://avatars.discourse-cdn.com/v4/letter/c/b19c9b/32.png) [@Cyrine](https://meta.discourse.org/u/Cyrine)
#### Post date: [22 Agosto 2020, 1:51pm UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/17 "2020-08-22T13:51:09Z")

</div>

Ciao, ho lo stesso problema (i custom\_fields vengono inviati nella console JS, ma non vengono salvati nel database). Ho usato il metodo `add_to_serializer(:basic_category, :default_tag, false ){object.custom_fields["default_tag"]}` nel mio file principale del plugin.

Consiglieresti ancora questa soluzione?

---

<div class="post-metadata">

### Author: ![fzngagan](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/fzngagan/32/259349_2.png) [@fzngagan](https://meta.discourse.org/u/fzngagan)
#### Post date: [22 Agosto 2020, 2:06pm UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/18 "2020-08-22T14:06:40Z")

</div>

Ci sono molte domande che sorgono qui. Campi personalizzati di cosa, innanzitutto?

---

<div class="post-metadata">

### Author: ![Cyrine](https://avatars.discourse-cdn.com/v4/letter/c/b19c9b/32.png) [@Cyrine](https://meta.discourse.org/u/Cyrine)
#### Post date: [22 Agosto 2020, 2:42pm UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/19 "2020-08-22T14:42:07Z")

</div>

Sto lavorando a un plugin per automatizzare la sincronizzazione dei gruppi di Discourse con LDAP. Ho aggiunto un campo personalizzato a Group (ldap\_dn) per salvare il nome del gruppo LDAP. Sto cercando di recuperare il valore del campo personalizzato da un campo di input che ho aggiunto nel plugin-outlet per l’iscrizione e salvarlo nel database per utilizzarlo in seguito.

Per fare questo, ho aggiunto quanto segue al mio file plugin.rb:

> Group.register\_custom\_field\_type(‘ldap\_dn’, :text)  
> Group.preload\_custom\_fields \<\< “ldap\_dn” if  
> Group.respond\_to? :preloaded\_custom\_fields

> if SiteSetting.groups\_sync\_enabled then  
> add\_to\_serializer(:group\_show, :custom\_fields, false) {  
> object.custom\_fields  
> }  
> end

Sono nuovo di Rails ed Ember, quindi non sono sicuro se ci sia un altro passaggio da compiere per salvare i custom\_fields nel database o dove risieda il problema.

---

<div class="post-metadata">

### Author: ![fzngagan](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/fzngagan/32/259349_2.png) [@fzngagan](https://meta.discourse.org/u/fzngagan)
#### Post date: [22 Agosto 2020, 2:46pm UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/20 "2020-08-22T14:46:29Z")

</div>

Penso che se aggiungi  
`register_editable_group_custom_field 'field_name'`  
al tuo plugin.rb

dovrebbe funzionare.

Nota:  
Il Serializer viene utilizzato per inviare i dati al client e non per riceverli.

---

<div class="post-metadata">

### Author: ![Cyrine](https://avatars.discourse-cdn.com/v4/letter/c/b19c9b/32.png) [@Cyrine](https://meta.discourse.org/u/Cyrine)
#### Post date: [22 Agosto 2020, 2:52pm UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/21 "2020-08-22T14:52:46Z")

</div>

Ah, ok! Sono un principiante, quindi questa potrebbe essere una domanda molto ‘ovvia’, ma per ricevere i dati, devo farlo tramite l’API?

---

<div class="post-metadata">

### Author: ![fzngagan](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/fzngagan/32/259349_2.png) [@fzngagan](https://meta.discourse.org/u/fzngagan)
#### Post date: [22 Agosto 2020, 2:54pm UTC](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913/22 "2020-08-22T14:54:27Z")

</div>

La mia soluzione darà il via libera al tuo campo quando i dati arriveranno al server. Quindi si tratta di ricevere i dati.

[Pagina seguente](https://meta.discourse.org/t/what-is-this-code-add-to-serializer-in-all-these-plugins/58913.md?page=2)
