Skip to content

Instantly share code, notes, and snippets.

@cutalion
Last active November 18, 2015 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cutalion/d42f55d82c4dd03d91e6 to your computer and use it in GitHub Desktop.
Save cutalion/d42f55d82c4dd03d91e6 to your computer and use it in GitHub Desktop.
Settings model for rails
class CreateSettings < ActiveRecord::Migration
def change
create_table :settings do |t|
t.string :key
t.string :human_name
t.text :value
t.timestamps null: false
end
end
end
.row
.col-sm-7
= simple_form_for [:admin, @setting] do |f|
.form-group
%h3
= @setting.human_name
= f.input :value, as: :text, input_html: { rows: 2 }
.form-actions
= f.button :submit, class: 'btn btn-primary'
= link_to 'Back', :back, class: 'btn btn-default'
%h4 Settings
%table.table.table-responsive
%thead
%tr
%th Value
%th Title
%th Action
%tbody
- @settings.each do |setting|
%tr
%td= setting.human_name
%td= setting.value
%td
= link_to 'Edit', edit_admin_setting_path(setting)
class Setting < ActiveRecord::Base
validates :key, :human_name, presence: true
after_save do
@@cached = nil
end
def self.value(key)
@@cached ||= Hash[ pluck(:key, :value) ]
@@cached[key]
end
end
class Admin::SettingsController < Admin::ApplicationController
before_action :set_setting, only: [:edit, :update]
def index
@settings = Setting.order('human_name asc')
end
def edit
end
def update
if @setting.update(settings_params)
redirect_to admin_settings_path, notice: 'Setting was successfully updated.'
else
render :edit
end
end
private
def set_setting
@setting = Setting.find(params[:id])
end
def settings_params
params.require(:setting).permit(:key, :human_name, :value)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment