Created
July 31, 2018 00:09
-
-
Save jmoglesby/538046a5898fa81e41bcc73142973162 to your computer and use it in GitHub Desktop.
Example code: Controller I am working on for forms that post to an external API (Airtable) when submitted.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CalibrationFormsController < ApplicationController | |
# Need not be a registered user to submit a calibration form | |
skip_before_action :authenticate_user! | |
def form | |
# limit current forms available for testing | |
valid_forms = ['','straight_edge', 'oven'] | |
raise ActionController::UnknownAction unless valid_forms.include?(params[:id]) | |
@title = params[:id].gsub('_',' ').titlecase | |
@form_to_render = params[:id] | |
end | |
def submit_form | |
# Set @table_name and @client_key | |
set_airtable_data | |
# decanter gem converts record_params data types to appropriate types for Airtable fields, | |
# as defined in app/decanters/calibration_forms_decanter.rb | |
decanted_params = CalibrationFormsDecanter.decant(record_params) | |
# Hit Airtable post API with decanted form params converted to json; store response | |
response = Net::HTTP.post URI("https://api.airtable.com/v0/appyyy.../#{@table_name}"), | |
{fields: decanted_params}.to_json, | |
"Authorization" => "Bearer #{@client_key}", | |
"Content-type" => "application/json" | |
# debugging | |
unless response.kind_of?(Net::HTTPSuccess) | |
Rails.logger.info response.code | |
Rails.logger.info response.body | |
end | |
# On success, present cleared form and notice of success | |
if response.kind_of?(Net::HTTPSuccess) | |
redirect_to cal_form_path(params[:cal_form_data][:type]), notice: "Record was successfully saved." | |
end | |
end | |
private | |
def set_airtable_data | |
# API key for Speedie Airtable account | |
@client_key = "keyzzz..." | |
# Set @table_name from form URL params (pluralized) - **Be sure Airtable Title matches** | |
@table_name = params[:cal_form_data][:type].gsub('_','%20').titlecase + 's' | |
end | |
def record_params | |
# Submit all data gathered by form except 'type', since that is only | |
# used to find the right table in Airtable | |
params.require(:cal_form_data).except(:type).permit! | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment