0

How to extract values present in array of multiple object's using jbuilder.?

i have an array of multiple objects.

@array1= [ ]
#pushed different types of objects into this array.
if xyz
@array1 << object_type1 # having fields id,f_name
else 
@array1 << object_type2 # having fields id,l_name

Now in jbuilder i want

json.array! @array1 do |myarray|
 json.id myarray.id
 json.name myarray.f_name || myarray.l_name # how to check object type here 
end

when i try this it is giving me error like

undefined method `l_name' for #<Object_type1:0xb496eda8>

How to check or tell jbuilder to which objecttype it has to use for name field.?

Aparichith
  • 1,452
  • 4
  • 20
  • 40

2 Answers2

1

i don't know whether it is a correct way or not but i tried and got what i wanted

 json.array! @array1 do |myaarray|
     if myarray.class == ObjectType
       json.name myarray.f_name
       json.id myarray.id
      else
       json.name myarray.l_name
       json.id myarray.id
      end  
   end
Aparichith
  • 1,452
  • 4
  • 20
  • 40
1

If both of your ObjectTypes are ActiveRecord models, you can do something a bit cleaner like:

json.array! @array1 do |myarray|
  json.name myarray.has_attribute? "f_name" ? myarray.f_name : myarray.l_name
  json.id myarray.id
end

This checks if myarray has an attribute of f_name and if it does uses that, otherwise we know it's the other ObjectType so we use l_name. If you haven't seen a one line if/else statement like this before, the syntax I'm using is:

<condition> ? <if_true> : <if_false>

So you can do things like:

@post.nil? ? return "No post here" : return "Found a post"

Or you can add a method to each of your ObjectTypes in their models like:

def name
  l_name # or f_name, depending on which ObjectType it is
end

Then you could do:

json.array! @array1 do |myarray|
  json.name myarray.name
  json.id myarray.id
end
Saul
  • 911
  • 1
  • 8
  • 19