Rails - how to expose attr_accessor when collecting all attributes

205 Views Asked by At

I am using the gon gem to get access to model objects in the front end. So in my controller I have something like this:

gon.items = @items

This isn't really a gon issue, basically gon.items is just an array of all @items where each array object n has all the attributes of the item n, just as if we were to do @items[n].inspect

I realized that I want to build a new attribute that's a helper for the front end, so I add this attribute, let's just say helper_attr as an attr_accessor on Class Item. Now in the controller, I am building it like so:

gon.items = @items
gon.items.each do |item|
  item.helper_attr = ...... 
end

puts gon.items.map { |i| i.helper_attr }

I notice that in the controller, the puts is correctly showing that helper_attr has indeed been built correctly and is available. However in the front end gon.items doesn't have the attribute helper_attr.

Is there a way to get it to show, without having to do clunky manual building?

# manual building example, instead of gon.items = @items, would do something like
gon.items = []
@items.each do |item|
  built_item = {}
  Item.attribute_names.each do |attr_n|
    built_item[attr_n] = item.send(attr_n)
  end
  built_item["#{helper_attr}"] = .....
  gon.items << built_item
end
0

There are 0 best solutions below