title: How do I set and save to a Rails API a Backbone collection nested within a Backbone Model?
body: <p>I want to nest a Backbone collection (Profiles) within a Backbone Model (Guild), and populate this collection with one Profile model (to start with).</p>
  <p>My goal is that when a user creates a new Guild, the model corresponding to this user should be added to the &quot;users&quot; attribute of the Guild.</p>
  <p>Therefore in my View I call a createGuild function that is defined within my model, which takes as an argument the model for the Profile of the logged in user.</p>
  <pre><code>createGuild(
      attrs: CreatableGuildArgs,
      profile: Backbone.Model,
      error: (errors: string[]) =&gt; void,
      success: () =&gt; void
    ) {
  
      this.set(attrs);
      this.set('users', new Profiles());
      this.get(&quot;users&quot;).add(profile);
  
      console.log(this.get(&quot;users&quot;).length);
      console.log(this.get(&quot;users&quot;).at(0));
  
      this.save(
        {},
        {
          url: this.urlRoot(),
  
          success: () =&gt; success(),
          error: (_, jqxhr) =&gt; {
            error(this.mapServerErrors(jqxhr?.responseJSON));
          },
        }
      );
    }
  </code></pre>
  <p>The two console.logs work fine within my createGuild function: I see a Profiles collection populated with one user profile, of length 1.</p>
  <p>However, the call to the save function is not working and returns the following error in my terminal :</p>
  <pre><code>Started POST &quot;/guilds&quot; for 172.18.0.1 at 2020-11-23 19:05:56 +0000
  Cannot render console from 172.18.0.1! Allowed networks: 127.0.0.0/127.255.255.255, ::1
   Processing by GuildsController#create as JSON
  Parameters: {&quot;name&quot;=&gt;&quot;gsdfgdhtfg&quot;, &quot;ang&quot;=&gt;&quot;GDG&quot;, &quot;users&quot;=&gt;&quot;[object Object]&quot;}
  Completed 500 Internal Server Error in 7ms (ActiveRecord: 0.0ms | Allocations: 2121)
  
  NoMethodError (undefined method `each' for &quot;[object Object]&quot;:String):
    
  app/controllers/guilds_controller.rb:15:in `create'
  </code></pre>
  <p>In my chrome console I get : &quot;Uncaught TypeError: Cannot convert undefined or null to object&quot;</p>
  <p>Here are my Rails models :</p>
  <pre><code>class Guild &lt; ApplicationRecord
      has_one_attached :img
      has_many :users
      accepts_nested_attributes_for :users
  
      validates :img, blob: { content_type: :image }
      validates :name, presence: true, uniqueness: true, length: {minimum: 5, maximum: 20}
      validates :ang, presence: true, length: {minimum: 2, maximum: 5}
  end
  
  class User &lt; ApplicationRecord
      has_one_attached :avatar
      belongs_to :guild, optional: true
  
      validates :avatar, blob: { content_type: :image, size_range: 1..5.megabytes }
      validates :name, presence: true
      validates :name, length: {minimum: 3, maximum: 32}
      validates :login, presence: true, uniqueness: true
  end
  </code></pre>
  <p>And the Rails controller for the create method of guild:</p>
  <pre><code>  def create
      @guild = Guild.create(guild_params)
      if @guild.save
          @guild
      else
          render json: @guild.errors, status: :unprocessable_entity
      end
    end
  
    private
  
    def guild_params
      params.permit(:name, :ang, :img, :users)
    end
  </code></pre>
  <p>And here is my json.jbuilder files :</p>
  <ul>
  <li>_guild.json.jbuilder :</li>
  </ul>
  <pre><code>json.extract! guild, :id, :name, :ang, :points, :atWar, :created_at, :updated_at
  json.img_url url_for(guild.img) if guild.img.attached?
  json.users guild.users do |json, user|
    json.partial! user
  end
  </code></pre>
  <ul>
  <li>create.json.jbuilder :</li>
  </ul>
  <pre><code>json.partial! &quot;guilds/guild&quot;, guild: @guild
  </code></pre>
  <p>And finally, here is my complete Guild model :</p>
  <pre><code>export default class Guild extends Backbone.Model {
  
    constructor(options?: any) {
      super(options);
    }
  
    urlRoot = () =&gt; &quot;http://localhost:3000/guilds&quot;;
  
    sync(method: string, model: Guild, options: JQueryAjaxSettings): any {
      if (method == &quot;create&quot;) {
        var formData = new FormData();
  
        _.each(model.attributes, function (value, key) {
          formData.append(key, value);
  
        });
        _.defaults(options || (options = {}), {
          data: formData,
          processData: false,
          contentType: false,
        });
      }
      return Backbone.sync.call(this, method, model, options);
    }
  
    createGuild(
      attrs: CreatableGuildArgs,
      profile: Backbone.Model,
      error: (errors: string[]) =&gt; void,
      success: () =&gt; void
    ) {
  
      this.set(attrs);
  
      this.set('users', new Profiles());
      this.get(&quot;users&quot;).add(profile);
  
      console.log(this.get(&quot;users&quot;).length);
      console.log(this.get(&quot;users&quot;).at(0));
  
      this.save(
        {},
        {
          url: this.urlRoot(),
  
          success: () =&gt; success(),
          error: (_, jqxhr) =&gt; {
            error(this.mapServerErrors(jqxhr?.responseJSON));
          },
        }
      );
    }
  
    mapServerErrors(errors: Record&lt;string, string[]&gt;) {
      return Object.keys(errors).map((key) =&gt; `${key} ${errors[key].join(&quot;,&quot;)}`);
    }
  }
  </code></pre>
  <p>Does anyone know how to fix this?</p>
  <p>Thank you</p>