fast_jsonapi icon indicating copy to clipboard operation
fast_jsonapi copied to clipboard

has_one block optional returns error

Open krzkrzkrz opened this issue 7 years ago • 4 comments

I have the following defined in a serializer:

class ArticleSerializer
  include FastJsonapi::ObjectSerializer

  set_key_transform :dash

  set_type : :articles

  has_one :last_chat_message, record_type: :'chat-messages', optional: true, serializer: ChatMessage do |object, params|
    object.chat_messages.where(priority: params[filter][priority]).last
  end
end

ChatMessageSerializer looks like:

class ChatMessageSerializer
  include FastJsonapi::ObjectSerializer

  set_key_transform :dash

  set_type : 'chat-messages'

  attributes :message, :created_at, :updated_at

  belongs_to :article
  belongs_to :user
end

ArticlesSerializer.new(Article.find(1), {}).serialized_json returns with:

NoMethodError: undefined method `id' for nil:NilClass
from /Users/foobar/.rbenv/versions/2.3.6/lib/ruby/gems/2.3.0/gems/fast_jsonapi-1.2/lib/fast_jsonapi/serialization_core.rb:185:in `fetch_id'

krzkrzkrz avatar Jul 03 '18 16:07 krzkrzkrz

This works if articles with id 1 has at least one chat message. But if not, then the error shows. I feel like has_one is ignoring optional: true.

As in, its always expecting an id to be present

krzkrzkrz avatar Jul 03 '18 19:07 krzkrzkrz

@krzkrzkrz i dont think we have the optional: true flag implemented. If you have sometime please take a stab at it.

shishirmk avatar Jul 17 '18 03:07 shishirmk

I'm having the same problem, the has-one association assumes that an object is always present.

gbrlmrllo avatar Jul 17 '18 17:07 gbrlmrllo

@krzkrzkrz @shishirmk - I can take this up but I don't feel this is something that the serializer shouldn't be responsible for. This has more to do with checking the data sanity before serializing. Like

  has_one :last_chat_message, record_type: :'chat-messages', serializer: ChatMessage do |object, params|
	if object.chat_messages.present?
      object.chat_messages.where(priority: params[filter][priority]).last
	else
	  nil
	end
  end

Thoughts?

manojmj92 avatar Jul 20 '18 14:07 manojmj92