David
David

Reputation: 1330

How to createRecord with belongsTo association with Ember.js & Rails?

I'm having trouble with a belongsTo association and sending a foreign key to my Rails controller with Ember.js and ember-data. My Ember.js controller will send the Project name to the Rails controller, but not the client_id value. In the Rails controller, params[:project][:client_id] comes through as nil.

Help! Where am I going wrong?

Models:

DA.Project = DS.Model.extend
  name: DS.attr('string')
  client: DS.belongsTo('DA.Client')

DA.Client = DS.Model.extend
  name: DS.attr('string')
  projects: DS.hasMany('DA.Project')

Controller:

DA.ProjectsController = Em.ArrayController.extend  
  createProject: (project) ->
    @transaction = DA.store.transaction()
    p = @transaction.createRecord(DA.Project, project)
    validation_errors = p.validate()

    if validation_errors
      DA.displayError validation_errors
    else
      @transaction.commit()

View:

DA.ProjectsNew = Em.View.extend
  tagName: 'form'
  templateName: 'projects/new'

  init: ->
    @_super()

  didInsertElement: ->
    @_super()

  submit: (event) ->
    event.preventDefault()
    project = {}
    project.name = @get('name')
    project.client = @get('client_id')

    DA.ProjectsController.createProject(project)

Template:

{{view Em.TextField valueBinding="view.name" placeholder="Project Name" tabindex="1"}}
{{view Em.TextField valueBinding="view.client_id" placeholder="Client ID" tabindex="2"}}
<button type="submit">Create</button>

Upvotes: 4

Views: 1984

Answers (2)

Pascal Zajac
Pascal Zajac

Reputation: 3027

Beware that, depending upon how you are binding the thing that lets you choose an object to associate with the object you are creating, Ember may automatically provide the object for you when you only expect to get the ID. For example using the Ember.Forms.Select view binding, the value of client_id in this example would be the actual Client object instance, rather than just the ID.

If you then blindly use this object in a App.store.find() call, you'll get back a promise object that never gets fulfilled, with the ID set as a serialisation of the original object. If you then try to commit this, it will attempt to persist something like:

"field_id":"<App.Type:ember123:1>"

Upvotes: 2

St&#233;phane Blond
St&#233;phane Blond

Reputation: 810

In the submit function, project.client is assigned an id instead of a DA.Client instance. If the DA.Client instance is supposed to pre-exist, you may get it with DA.store.find(DA.Client, @get('client_id')).

Upvotes: 3

Related Questions