Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample Controller Pattern with Turbo
# frozen_string_literal: true
module Tools
class ClientVariablesController < Tools::ToolsController
before_action :set_client_variable, except: [:create]
before_action :set_client
def edit
render turbo_stream: [
turbo_stream.replace('variables-form', partial: 'form')
]
end
def create
@client_variable = ClientVariable.new(client: @client)
@client_variable.assign_attributes(client_variable_params)
flash.now.notice = 'Variable saved'
create_response(@client_variable.save)
end
def update
@client_variable.assign_attributes(client_variable_params)
flash.now.notice = 'Variable updated'
create_response(@client_variable.save)
end
def destroy
create_response(@client_variable.destroy)
end
private
def set_client
@client = Client.find(params[:client_id]) if params[:client_id]
@client = @client_variable.client if @client_variable
end
def set_client_variable
@client_variable = ClientVariable.find(params[:id])
end
def client_variable_params
params
.require(:client_variable)
.permit(:tag, :value, :data_type)
end
def create_response(success)
if success
@client_variable = ClientVariable.new(client: @client)
@client_variables = ClientVariable.for_client(@client.id)
render turbo_stream: [
turbo_stream.replace('flash', partial: 'tools/shared/flash'),
turbo_stream.replace('variable-form', partial: 'form'),
turbo_stream.replace('variable-table', partial: 'table')
]
else
flash.now.notice = nil
flash.now.alert = "Error: #{@client_variable.errors.first.message}"
render turbo_stream: turbo_stream.replace('flash', partial: 'tools/shared/flash')
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment