0

I have a user model with serialized attributes. I also have a JSON API built with Grape using ActiveModel::Serializer to serialize the JSON. Here are the relevant snippets of code:

class User < ActiveRecord::Base
  serialize :about_me
  serialize :favorites
end

class UserSerializer < ActiveModel::Serializer
  attributes :id, :email, :password, :token, :about_me, :favorites
end

When I interact with an instance of the User class via rails console, everything works fine. For example I can do:

2.2.1 :003 > user.about_me = {some_key: "some value", other_key: "other value"}
 => {:some_key=>"some value", :other_key=>"other value"} 
2.2.1 :004 > user.save
   (0.3ms)  begin transaction
  SQL (1.0ms)  UPDATE "users" SET "about_me" = ?, "updated_at" = ? WHERE "users"."id" = ?  [["about_me", "---\n:some_key: some value\n:other_key: other value\n"], ["updated_at", "2015-08-27 17:08:45.459413"], ["id", 4]]
   (7.2ms)  commit transaction
 => true 

It serializes just fine, everything works.

However, when the data goes through the serializer via the API. I get:

{error: "about_me is invalid"}

I have even tried adding a wrapper method that the api uses rather than #update_attributes, I tried using a custom method:

def update_attributes_from_params(params)
  self.about_me = params[:about_me] if params[:about_me].present?
  self.email = params[:email] if params[:email].present?
  self.password = params[:password] if params[:password].present?
  self.your_style = params[:your_style] if params[:your_style].present?
  self.favorites = params[:favorites] if params[:favorites].present?
  self.save
end

This method does what I want from the console, but again, through the serializer does not work. I just get the invalid error.

Any suggestions, help, hints, or feedback would be appreciated.

Matt
  • 1
  • I would recommend that you build your API to either use rails style parameters `params[:user][:email]` or use the [JSONAPI format](http://jsonapi.org/): `params[:data][:attributes][:email]`. Using "unwrapped" keys gives you a false sense of simplicy - it gives nice short code but buckles at the first sight of any kind of complexity. – max Aug 27 '15 at 17:57
  • What does params[:about_me] look like in your controller? Is it a hash? – dinomix Aug 27 '15 at 18:41
  • 1
    I ended up splitting about_me into a separate model with a has_one relationship and it seems to work great now. However, I don't understand why that's the case. – Matt Sep 01 '15 at 20:27
  • I have another case that has now come up and I really need to get this working, but I don't understand why it's not working in order to attempt to fix it. An example of params is: {email: "test@example.com", about_me: {some_key: "some value", other_key: "other value"}} – Matt Sep 01 '15 at 20:32

0 Answers0