I am trying to use a jbuilder to render a json response for a TypeCar object in my response
class TypeCar < ActiveRecord::Base
attr_accessible :name
belongs_to :car_alias, foreign_key: :name, primary_key: :name, counter_cache: true
has_one :main_car, through: :car_alias, foreign_key: :name, primary_key: :name
end
In the json for the TypeCar partial, "views/api/type_cars/_type_cars.json.jbuilder",
json.extract! type_car, :name
json.main_car Array.wrap(type_car.main_car) do |main_car|
json.partial! "api/main_cars/main_cars", main_car: main_car
end
And the main car partial in "api/main_cars/_main_cars.json.jbuilder"
json.extract! main_car, :more_info, :name, :id
The view that uses the _type_car partial, returns the following
{
name: test,
main_car: [
{
more_info: "Lorem Ipsum",
name: "New",
id: 198
}
]
I am guessing that the for main car attribute is a hash in a single object array because of wrapping up the array. But I would like the remove this as it is one more extra level of nesting that is not needed. So I would just prefer a plain dictionary instead of a hash.
The reason I had to wrap the object in an array and pass it to an enumerable was because nothing else seemed to work.
This...
json.extract! type_car, :name
json.main_car do
json.partial! "api/main_cars/main_cars", main_car: type_car.main_car
end
Gives this error...
undefined method `more_info' for nil:NilClass
And this:
json.extract! type_car, :name
json.main_car type_car.main_car do |main_car|
json.partial! "api/main_cars/main_cars", main_car:main_car
end
Gives this error:
undefined method `map' for #<MainCar:>
Even trying stuff like type_car.main_car.id within the type car partial returns the nil problem.
Really appreciate all the help and guidance, thanks!
Aucun commentaire:
Enregistrer un commentaire