contentful / contentful_model

A lightweight wrapper around the Contentful api gem, to make it behave more like ActiveRecord
MIT License
44 stars 42 forks source link

Association sometimes returns a hash #114

Closed pezholio closed 6 years ago

pezholio commented 6 years ago

I have two models, BlogPost and Comment

class BlogPost < ApplicationRecord
  self.content_type_id = 'blogPost'

  belongs_to_many :comments
end
class Comment < ApplicationRecord
  self.content_type_id = 'comment'

  has_one :associated_record, class_name: 'BlogPost'
end

A BlogPost has many Comments, and this seems to work most of the time. However, when running my tests, from time to time, when I try and get the associated blog post from a comment, ContentfulModel returns a hash, rather than the actual model:

post = BlogPost.create(title: slug, subheading: 'subheading', date: Date.today, slug: slug, body: 'Some Text', author: author)
post.publish
comment = Comment.create(name: 'foo', email: 'foo@bar.baz', organisation: '', comment: 'Hello', associated_record: post)
comment.publish
comment.associated_record
#=> {"sys"=>{"type"=>"Link", "linkType"=>"Entry", "id"=>"4GX6dhjbrGGwYu8IKiC4Ma"}}

Any ideas as to where I'm going wrong?

dlitvakb commented 6 years ago

Hey @pezholio,

Which version of the gem are you using?

Cheers

pezholio commented 6 years ago

1.0.0 👍

dlitvakb commented 6 years ago

@pezholio It's because what you get as a response from create and publish is a CMA object, there the references are not hydrated. If you want the full reference, you should do Comment.find(comment.id).associated_record, which is the CDA object.

Cheers

pezholio commented 6 years ago

Ah, that makes sense, thanks! 👍