rabl
rabl copied to clipboard
Bug in accessing object in child block
According to the docs it's possible to pass the current object to a child block like so:
object @user child :posts do |user| attribute :title unless user.suspended? end
What I'm seeing is that the block argument is not the "user" but rather the "posts" ActiveRecord relation. I'm not sure if this a bug in the docs or one in the implementation. If the former, how does one access the user object when processing its posts?
+1 we're seeing this in the latest version
:+1:
+100. Is no one else getting this error?
Seems pretty big to me.
+1
Can anyone take a look at the "why" this is happening? It does seem like a pretty big regression if this is happening. Can someone play around with older versions and identify when this regression happened? Maybe @DouweM might be able to take a look eventually too. Thanks.
I'm almost sure this has always been the behavior; the documentation has just been incorrect. In the commit where this feature was introduced, https://github.com/nesquena/rabl/commit/a895fccb7efaeb3fc9ff3521b7c1350b279e772b, you can see it's passing @_data
to the block, which is the child-object at this point. The spec may be a little misleading, but here too, the passed object is @user-the-argument-to-child
, not @user-the-root-object
.
I see, thanks for investigating that. Looks like the docs are at fault leading to the confusion and the years since I implemented that have made the details of how that worked hazy.
Can you or anyone implement this? I think many users are waiting for this feature.. Would be great :-)
Note that the original pull request (https://github.com/nesquena/rabl/pull/300) explicitly calls for the current behavior, not the documented behavior, and it seems unwise to introduce such a backward-incompatible change seeing as it's worked this way for 3 years.
We could add a second argument to be passed to the block which would be the root object "one level up" rather than the root object to the child call:
object @user
child :posts do |posts, user|
attribute :title unless user.suspended?
end
I agree that changing the current behavior would lead to confusion.
Adding a second argument to access the correct object in my collection would solve my problem.
+1
anyone know a work around for this so you can access the parent?