Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

partial in Jbuilder is not working with associations

I am writing partials using jbuilder to return json data. I have an module in which I am returning data per record in show method and all records in index. But all record things is not working here what I did my show method in controller

def index
@signals = Signal.all.paginate(:page => params[:page], :per_page => 10)

end

def show
 @signal = Signal.find(params[:id])
end

Here is my partial _signal.json_jbuilder

json.(@signal, :id, :power)
json.user do
 json.first_name @signal.user.first_name
json.last_name @signal.user.last_name
 json.email @signal.user.email
end
json.location @signal.signal_location, :latitude, :longitude
json.device do
json.model @signal.device.phonemodel
json.os_version @signal.device.os_version
json.os_type @signal.device.os_type
json.sim_card_provider @signal.device.sim_card_provider
end

now I am using this partial in my show.json.jbuilder and index.json.jbuilder here is my show.json.jbuilder

json.partial! 'signals/signal', signal: :@signal 

it is working fine but when I use this partial in index.json.jbuilder here is my index.json.jbuilder

json.partial! partial: 'signals/signal', collection: @signals, as: :signal

it says undefined @signal.user.first_name. It is reaching inside partial but can not reach associations. I checked logs..but nothing very helpful... stuck with it since long...help appreciated

like image 657
JNI_OnLoad Avatar asked Dec 25 '22 14:12

JNI_OnLoad


1 Answers

You should change your partial to use local variable.

For example

json.(signal, :id, :power)
json.user do
  json.first_name signal.user.first_name
  json.last_name signal.user.last_name
  json.email signal.user.email
end
json.location signal.signal_location, :latitude, :longitude

And in show.json.jbuilder

json.partial! 'signals/signal', signal: @signal

in index.json.jbuilder

json.partial! partial: 'signals/signal', collection: @signals, as: :signal
like image 116
lazywei Avatar answered Dec 28 '22 06:12

lazywei