# Gemfile
gem 'polymorph'
# config/routes.rb
# Rails.application.routes.draw do
mount Polymorph::Engine, at: '/'
# end
If you skip it anybody could use new functions.
# ininitalizers/polymorph.rb
Polymorph.configure do |config|
config.authorize = lambda do |controller|
controller.authenticate_user!
end
end
Orders models on their position column via ordered
scope. If you are using it
you would have to add some additional dependencies:
Orderable
user drag-n-drop depends on jQuery UI.
# Gemfile
gem 'jquery-ui-rails'
It also needs some js helpers:
# application.js
//= require jquery-ui/sortable
//= require polymorph/polymorph
And an optional stylesheet for changing cursor shape:
/* application.css
* = require polymorph
*/
Default selector is .admin [data-orderable]
so you have to add .admin
class somewhere for an authorized user.
body class=(current_user.admin? && 'admin')
Orderable items got to have its #id
in HTML id
element
div_for(model)
or
div id=dom_id(model)
Add position:integer
to a model schema
rails g migration add_position_to_model position:integer
rake db:migrate
Include Polymorph::Orderable
in the Model
class
# models/model.rb
# class Model < ActiveRecord::Base
include Polymorph::Orderable
# end
Don't forget to use ordered
scope
# controllers/models_controller.rb
def index
@models = Model.ordered
end
HTML selector
# index.html.slim
div data-orderable=polymorph.orderable_path(Model)
= render @models
Axis limits movement alone X or Y axes:
data-orderable-axis="y"
Items is an additional subselector for items that will be serialized and moved:
data-orderable-items="> .block"
This module provides paranoid delete akin to Paranoia gem. But there is one important difference. There are no callbacks.
It simply updates deleted_at
so you can restore deleted entries with
associations associations intact.
First create a migration:
rails generate migration AddDeletedAtToModel deleted_at:datetime:index
rake db:migrate
Add concern to model:
# models/model.rb
# class Model < ActiveRecord::Base
include Polymorph::Paranoid
# end
You need to add Polymorph::Application
helper to Application Controller.
# controllers/application_controller.rb
# class ApplicationController < ActionController::Base
helper Polymorph::ApplicationHelper
# end
Included module sets up default_scope
so soft-deleted entries are skipped.
Additional class method paranoid_destroy
is added to the parent class in case
you want to wrap your own stuff.
# controllers/model_controller.rb
# def destroy
@model.paranoid_destroy
# end
This one sets published_at
in the same vein as with Paranoid.
First a migration:
rails generation migration AddPublishedAtToModel published_at:datetime:index
rake db:migrate
Add concern:
include Polymorph::Publishable
This module adds 'published' and 'unpublished' scope.