简体   繁体   中英

Using a referenced model object in JBuilder Ruby on Rails

I am trying to learn Ruby on Rails and have come stuck in trying to get a slightly more complex JSON response than from the tutorials I have been following.

I have two models as follows:

class Worker < ActiveRecord::Base
  has_many :tips
end

and

class Tip < ActiveRecord::Base
  belongs_to :worker
end

So each Worker has many tips.

My controllers are as follows:

class WorkersController < ApplicationController

  skip_before_filter :verify_authenticity_token

  def index
    @workers= Worker.all
  end

  def show
    @worker= Worker.find(params[:id])
    @tips = @worker.tips
  end

end

and

class TipsController < ApplicationController

  skip_before_filter :verify_authenticity_token

  def index
    @tips = Tip.all
  end

  def show
    @tip = Tip.find(params[:id])
  end

end

So as you can see in my WorkersController I assign all the tips from a Worker to the @tips variable.

Now I want to get this information returned in JSON format and I am using partials to try and achieve this.

Here is the Worker partial:

json.(worker, :id, :name, :location, :image)

And here is the tips partial:

json.(tip, :id, :title, :summary, :rating)

Both are under the views/layouts/workers directory

And here is my JSON that I actually want returned (it is in a file called show.json.jbuilder:

json.worker do
  json.partial! 'worker', worker: @worker
  json.tips do
    json.partial! 'tip', tip: @tip
  end
end

However this gives me a 500 internal server error.

If I leave it like this:

json.themepark do
  json.partial! 'themepark', themepark: @themepark
end

I get the JSON but of course I am missing the data I need. I'm not sure what steps to take next to try to figure out what I am doing wrong so wondering if anyone can help me out with my mistake?

The 500 is probably because you don't have @tip defined in workers_controller#show .

In order to successfully render your existing objects, you'd need to do something like:

json.worker do
  json.partial! 'worker', worker: @worker
  json.tips do
    json.partial! 'tip', collection: @tips, as: :tip
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM