Last active
September 28, 2021 16:13
-
-
Save DaveSanders/58d222f81619bc790e804dc94eda0ffb to your computer and use it in GitHub Desktop.
Sample Controller Pattern with Turbo
This file contains 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
# 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