nesquena / rabl

General ruby templating with json, bson, xml, plist and msgpack support
http://blog.codepath.com/2011/06/27/building-a-platform-api-on-rails/
MIT License
3.64k stars 334 forks source link

Access @object.id when using a collection? #642

Closed ethicalhack3r closed 9 years ago

ethicalhack3r commented 9 years ago

In the following rabl view, how do I access the @plugin.id if @plugin is a collection?

show.rabl:

object false

collection @plugin # this is a collection
attributes :name, :latest_version, :last_updated, :popular

plugin_id = @plugin.id # I need this but within the fixed_in node

child(:vulnerabilities, object_root: false) do
  extends 'api/v2/vulnerabilities'

  node(:fixed_in) do |vulnerability|
    # I need the @plugin.id here for the below query
    PluginVulnerability.where(vulnerability_id: vulnerability.id, plugin_id: plugin_id).first.fixed_in
  end
akodkod commented 9 years ago

@ethicalhack3r, try root_object, it's works for me.

ethicalhack3r commented 9 years ago

Thanks!

I think my problem here is that I was trying to use the same view for both a single object (called from a controller) and a collection of objects (called from elsewhere in my codebase).

I was doing this from elsewhere in my codebase:

Rabl::Renderer.new('api/v2/wordpresses/show', Wordpress.all, view_path: 'app/views', format: 'json').render

I solved my problem by passing a single object to the view rather than a collection. Calling Rabl::Renderer for each object and then creating an Array/hash/whatever from that.

Wordpress.all.each do |wordpress|
  Rabl::Renderer.new('api/v2/wordpresses/show', wordpress, view_path: 'app/views', format: 'json').render
end