user3765411
user3765411

Reputation: 11

Rails 4 *.json.jbuilder files ignored

In my Rails 4.1.1 app (which has the jbuilder gem included), json views always output all columns in the table, ignoring the app/views/[model]/*.json.jbuilder files.

In routes.rb, I have:

  resources :workshops do
    resources :memberships
    resources :events
  end

In events_controller.rb, I have:

  # GET /workshop/:workshop_id/events
  # GET /workshop/:workshop_id/events.json
  def index
    @events = @workshop.events    
    respond_to do |format|
      format.html 
      format.json { render json: @events }
    end
  end

I set the @workshop variable in a "before_action" in the controller.

When I visit /workshops/f00/events, it displays in HTML format as expected.

If I make the file, app/views/events/index.json.jbuilder:

json.events do
end

...when I visit /workshops/f00/events.json, I expect that the output would be empty. However, I get the contents of the entire @events in JSON format.

What I would like to see is only particular fields being output, given a app/views/events/index.json.jbuilder that contains:

json.array!(@events) do |event|
  json.extract! event, :id, :title, :description
  json.start event.starts_at
  json.end event.ends_at
  json.url workshop_event_url([@workshop, event], format: :json)
end

... but no matter the contents of the .jbuilder file, the output is always the same. Could anyone tell me why my .jbuilder file is being ignored, and how to get it working?

Upvotes: 1

Views: 1612

Answers (1)

vich
vich

Reputation: 11896

The line format.json { render json: @events } will always render the @events array since the url /workshops/f00/events accepts both html and json formats and you're rendering @events when hitting the url with the json format.

If you want to render the data in app/views/events/index.json.jbuilder change:

respond_to do |format|
  format.html 
  format.json { render json: @events }
end

to:

respond_to do |format|
  format.html 
  format.json
end

By not rendering the @events array you rely on Rails to output whatever is in app/views/events/index.json.jbuilder.

Upvotes: 1

Related Questions