Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rabl Multi-model collection

I am using RABL to output a Sunspot/SOLR result set and the search results object is composed of multiple model types. Currently within the rabl view I have:

object false

child @search.results => :results do
  attribute :id, :resource, :upccode
  attribute :display_description => :description

  code :start_date do |r|
    r.utc_start_date.to_i
  end

  code :end_date do |r|
    r.utc_end_date.to_i
  end

end

child @search => :stats do
  attribute :total
end

The above works for a single model; however, when multiple model types are within the @search.results collection, it fails because both classes do not have the same instance methods. Does anyone know how to have different attributes based on the type? Ultimately, it would be nice to conditionally extend a different template within the results collection based on the type of object. Something like the below pseudo code:

child @search.results => :results do |r|
  if r.class == Product
    extends "product/base"
  else
    extends "some other class base"
  end
end
like image 813
ejlevin1 Avatar asked Nov 30 '11 15:11

ejlevin1


1 Answers

You can take full control with 'node' and avoid this issue entirely in the 'worst' case:

node :results do
  @search.results.map do |r|
    if r.is_a?(Product)
      partial("product/base", :object => r)
    else # render other base class
      partial("other/base", :object => r)
    end
  end
end

Does that help?

like image 165
Nathan Avatar answered Oct 03 '22 01:10

Nathan