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.?

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.