Nirmalya Ghosh
Nirmalya Ghosh

Reputation: 2530

Connecting Rails api association with Ember

I've two models: user and card.

When a user creates a new card, I want to associate the user with that card. (You can assume that the user_id is 1)

For the Rails part,

card.rb

class Card < ActiveRecord::Base
  has_and_belongs_to_many :users
end

user.rb

class User < ActiveRecord::Base
  has_and_belongs_to_many :cards
end

For the Ember part,

app/routes/card/new.js

  actions: {
    save(title, description) {
      let user = this.get('store').find('user', 1);

      const newCard = this.get('store').createRecord('card', {
        title,
        description,
        user
      });
      newCard.save().then((card) => {
        // go to the new item's route after creating it.
        this.transitionTo('card.card', card);
      });
    }
  }

Currently, I can associate them through the Rails console. I want to know how I can associate both of them through the Rails api and Ember data so that when I create a new card, it associates the current user along with that card.

Repo link (Rails): https://github.com/ghoshnirmalya/hub-server

Repo link (Ember): https://github.com/ghoshnirmalya/hub-client

Upvotes: 0

Views: 48

Answers (1)

Albin
Albin

Reputation: 3032

You need to update the code in your controller:

https://github.com/ghoshnirmalya/hub-server/blob/master/app/controllers/cards_controller.rb

In your create method you need to take the user id you receive and make the connection.

EDIT:

def create
  @card = Card.new(card_params)

  if @card.save
    @card.users << User.find(params[:data][:attributes][:user_id]) if params[:data][:attributes][:user_id] # this is my guess
    render json: @card
  else
    render json: @card, :status => 422
  end
end

Upvotes: 1

Related Questions