Nirmalya Ghosh Nirmalya Ghosh - 5 months ago 33
Ruby Question

Associate rails api and ember

On submitting, my Ember frontend is sending me data like this:

{
"data":{
"attributes":{
"title":"asd",
"description":"asd"
},
"relationships":{
"users":{
"data":[
{
"type":"users",
"id":"1"
}
]
}
},
"type":"cards"
}
}


Here, I want to associate between a
card
and a
user
when a new
card
is created.

app/controllers/cards_controller.rb

def create
@card = Card.new(card_params)

if @card.save
@card.users << User.find(params[:data][:relationships][:users][:data]) if params[:data][:relationships][:users][:data]

render json: @card
else
render json: @card, :status => 422
end
end

private

def card_params
params.require(:data).require(:attributes).permit(:title, :description)
end


The error in the Rails end is something like this:

DEPRECATION WARNING: Method to_a is deprecated and will be removed in Rails 5.1, as `ActionController::Parameters` no longer inherits from hash. Using this deprecated behavior exposes potential security problems. If you continue to use this method you may be creating a security vulnerability in your app that can be exploited. Instead, consider using one of these documented methods which are not deprecated: http://api.rubyonrails.org/v5.0.0/classes/ActionController/Parameters.html (called from create at /Applications/AMPPS/www/development/ideast/hub/hub-server/app/controllers/cards_controller.rb:16)
Completed 500 Internal Server Error in 24ms (ActiveRecord: 3.4ms)

NoMethodError (undefined method `join' for #<ActionController::Parameters:0x007f9b5549e380>
Did you mean? JSON):


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

Answer

I believe you should be able to customize your Ember adapters to send the correct data format.

However, here's a way I'd probably go about solving the current issue:

**The user_params method isn't so clean, I'd probably want to find a cleaner way of handling it.

def create
  @card = Card.new(card_params)

  if @card.save
    @card.users << User.find(user_params)

    render json: @card
  else
    render json: @card, :status => 422
  end
end

private

def user_params
   params.require(:data).require(:relationships).require(:users).permit(data: [:id]).require(:data).map(&:values)
end

def card_params
   params.require(:data).require(:attributes).permit(:title, :description)
end