partial in Jbuilder is not working with associations

jbuilder, json, partial-views, ruby-on-rails

Solution

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

Problem

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

Original source