fast_jsonapi
fast_jsonapi copied to clipboard
has_one block optional returns error
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'
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 i dont think we have the optional: true flag implemented. If you have sometime please take a stab at it.
I'm having the same problem, the has-one association assumes that an object is always present.
@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?