Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a different key name for an association attribute in rails api active model serializer

I am building a Rest API using rails-api and active-model-serializer to easily filter the required fields in the JSON. I am also using the has_one association in these serializers. All I wanted to know is how do I specify a different key name for the has_one attribute.

That is, I have two models say: Employee and Address, and there is a has_one :address in say EmployeeSerializer. The response that I get is:

{
  id: 1,
  address: {
   street: "some_street",
   city: "some_city"
  }
}

But I would like to get the following response:

{
  id: 1,
  stays: {
   street: "some_street",
   city: "some_city"
  }
}

I tried using has_one :address, :key => :stays, but that doesn't seem to work.

like image 822
swaroopsm Avatar asked Dec 30 '14 14:12

swaroopsm


1 Answers

@janfoeh is right on. I just tested this in version 0.8 and it works just fine

  1. gem "active_model_serializers", "~> 0.8.0" in your Gemfile
  2. Kill the server
  3. $bundle install
  4. has_one :address, key: "stays"
  5. Start the server back up

Works great!

As the documentation for the gem says (here), "you probably want to use version 0.8"

like image 161
Kalman Avatar answered Nov 19 '22 17:11

Kalman