I created a layout designer using Canvas. It is configured via a JSON file (eg. background to use, allowed fonts, colors, etc.). I'm trying to figure out how to tie it into a Rails application. I'm not sure where to look for information. The resources I found did not point me in a good direction. I need some general pointers on the following:
1) Let's say I have a product page setup. How would I send the JSON config info from my Model to the JS app?
2) How would I send a modified JSON file back from my js app to be saved in the DB?
3) Do I need to setup a JSON API for that? Is that what I need to look for?
Any pointers/links are appreciated.
Thank you,
Leo
You can send JSON to your js by using below in your rails controller:
result = xyz.select(:id, :xyz_name).all render :json => result
You can send JSON as it is from javascript to rails. rails will receive json as params[:key]
JSON support is built in, you don't need any separate set up.
Yes it sounds like you need to setup a JSON api. There are many ways to do it, but the way I like the most is to have a namespaced 'api' in the url that accepts json requests and returns json. Here's how:
Create a folder in your controllers called 'api' Make a controller in this folder called 'api_controller.rb' put this in that controller:
class Api::ApiController < ApplicationController
skip_before_filter :verify_authenticity_token
#before_filter :set_headers # may need to set headers as listed below
#before_filter :authenticate_apiKey # if you want to authenticate the user, use an authentication token
respond_to :json
def set_headers
# Please look up what each of these headers do before adding them.
# headers['Access-Control-Allow-Origin'] = *
# headers['Access-Control-Expose-Headers'] = 'ETag'
# headers['Access-Control-Allow-Methods'] = 'GET, POST, PATCH, DELETE, OPTIONS, HEAD'
# headers['Access-Control-Allow-Headers'] = '*,Content-Type'
# headers['Access-Control-Max-Age'] = '86400'
end
end
Then whatever controller you create inside the api folder, have it inherit from Api::ApiController instead of ApplicationController like usual.
In your controller actions, you can use 'render json: @object'
Just make sure to create a serialiazable_hash or to_json method in your models.
You will also need to update your routes file like so:
namespace :api, defaults: { :format => :json } do
# put your routes here
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.