문제

I'm trying to integrate JBuilder into Rails 3.2 project. I've installed the gem, and I've written a JBuilder file at app/views/books/index.json.jbuilder.

Here's my index action:

  def index

    @books = Book.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @books }
    end
  end

This seems to call the default as_json method of Book to render the response. What do I need to change to tell Rails to use my JBuilder template instead?

도움이 되었습니까?

해결책

Remove the block you're passing to format.json. You're causing it to ignore your jbuilder file and instead return the result of json: @books as a response. If you leave the block out:

respond_to do |format|
  format.html # index.html.erb
  format.json # no block here
end

Then Rails will fall back to its default handling of the response and look for a template in your view directory, it'll find the jbuilder file and render that as the response.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top