简体   繁体   中英

Rails - blank json file when using jbuilder

I'm trying to use jbuilder to create a json file from a list of events. It has to be in a specific format. Currently, no matter what I put in the jbuilder file, when you go to users/1/events.json, the file is blank (just {}).

I've tried putting a respond to block in the controller, but then that just returns the list of events in the wrong format.

I think that the routes have been done properly, because the log file says that the file myevents.json.jbuilder was rendered successfully when the url /users/1/myevents.json was requested. Plus, when the .html is requested, the myevents.html file shows up fine, with all the correct info in it.

I'm really stumped on this one, any help would be much appreciated!!

I'll list all relevant code in case anyone can pick something up:

events controller:

def myevents
    @events = current_user.events
end

myevents.json.jbuilder:

Jbuilder.encode do |json|
    json.timeline do
        json.headline current_user.first_name
        json.type "default"
        json.text "A Timeline"
        json.start_date
        json.array!(@events) do |event|
            json.start_date event.start_date
            json.end_date event.end_date
            json.headline event.headline
            json.text event.text
            json.asset do
                json.media event.media
                json.credit event.credit
                json.caption event.caption
            end
        end
    end
end

environment.rb:

Jbuilder.key_format :camelize => :lower

routes.rb:

match 'users/:id/events' => 'events#myevents'

The reason is because you need to put the following line into your RSPEC controller helper file:

config.render_views = true

I had the same issue: https://github.com/rails/jbuilder/issues/32

As far as I know you can just skip

Jbuilder.encode

Try without this block, maybe everything will be ok.

Figured it out. For some reason, it doesn't like the line Jbuilder.encode do |json|, even though that is what is listed in the documentation to use. Syntax of the response still isn't quite right though.

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