1

I have create a show method in tour controller and want to render the data from the database into json format. This the definition of the tour controller

class ToursController < ApplicationController

    respond_to :json

        def show    
            @tourcategory = Tourcategory.find(params[:id])
            @tours= @tourcategory.tours
            @tourcategories = Tourcategory.all
            render :layout => false

        end
    end

This is the definition of the show.html.haml view

    %h3 Tour for #{@tourcategory.title}
    = @tours.to_json

The output of this code is following:

[{"content":"dscfds","created_at":"2015-12-12T09:48:32Z","elementid":"test1","id":8,"jobid":2,"next_button_title":"next","priority":23,"title":"test1","updated_at":"2015-12-12T09:48:32Z"}]

But i just want to render the data in this kind of json format, following:

var tour = {
  id: "tour",
  steps: [
    {
      title: "abc",
      content: "Click this  Button.",
      target: "#abc",
      placement: "bottom",
      showNextButton: false,
      skipIfNoElement : true
    },
sadaf2605
  • 7,332
  • 8
  • 60
  • 103

1 Answers1

0

It's not clear what you're trying to achieve but it seems to me that you want to extract certain attributes from your @tours and group them as an array, if that's the case you can do something like this:

(list all the attributes you want inside t.attributes.slice())

tour = { id: "tour", steps: @tours.map { |t| t.attributes.slice("title", "content", "target") } }

and if you want to convert your keys from snake (underscore) to camel format:

tour = {
        id: "tour",
        steps: @tours.map {|t| t.attributes.slice("title", "content").map {|k,v| [k.camelize(:lower), v]}.to_h} 
       }
Amr Noman
  • 2,597
  • 13
  • 24
  • This just defines a variable, put it inside your controller's action (if you want to use it in your view, you'll have to make it an instance variable `@tour`) and then simply render it in your view like you did previously or do whatever you want with it. – Amr Noman Dec 12 '15 at 14:05
  • i have add this in my controller show method and do render on the show.html.haml view but it gives an error undefined method 'map' – Jaspreet Kaur Dec 12 '15 at 14:15