Jan Varljen
contacts = []
contacts += Person.all
contacts += Company.all
SELECT
people.id AS contactable_id,
'Person' AS contactable_type,
CONCAT_WS(' ', people.first_name, people.last_name) AS name,
FROM people
UNION
SELECT
clients.id AS contactable_id,
'Client' AS contactable_type,
clients.name AS name,
FROM clients
def people_sql
Person.select(
"people.id AS contact_id,
'Person' AS contact_type,
CONCAT_WS(' ', people.first_name, people.last_name) AS full_name"
).to_sql
end
def companies_sql
Client.select(
"clients.id AS contact_id,
'Client' AS contact_type,
name AS full_name"
).to_sql
end
def find
ActiveRecord::Base.connection.select_all(
query + " ORDER BY full_name " + limit_sql
)
end
def query
[people_sql, companies_sql].join(' UNION ')
end
def limit_sql
"LIMIT #{per_page} OFFSET #{offset}"
end
def offset
(page - 1) * per_page
end
CREATE VIEW contacts AS
SELECT
people.id AS contactable_id,
'Person' AS contactable_type,
CONCAT_WS(' ', people.first_name, people.last_name) AS name,
FROM people
UNION
SELECT
clients.id AS contactable_id,
'Client' AS contactable_type,
clients.name AS name,
FROM clients
class Contact < ActiveRecord::Base
belongs_to :contactable, polymorphic: true
default_scope { alphabetical }
scope :alphabetical, -> { order(name: :asc) }
private
def readonly?
true
end
end
Contact.all
Contact.alphabetical
Contact.first(10)
Contact.paginate(per_page: 10, page: 2)
Contact.where('name LIKE ?', "%#{query}%")
SELECT
people.id AS contactable_id,
'Person' AS contactable_type,
CONCAT_WS(' ', people.first_name, people.last_name) AS name,
FROM people
UNION
SELECT
clients.id AS contactable_id,
'Client' AS contactable_type,
clients.name AS name,
FROM clients
class CreateContactsView < ActiveRecord::Migration
def change
create_view :contacts
end
end
SELECT
people.id AS contactable_id,
'Person' AS contactable_type,
CONCAT_WS(' ', people.first_name, people.last_name) AS name,
deleted
FROM people
UNION
SELECT
clients.id AS contactable_id,
'Client' AS contactable_type,
clients.name AS name,
deleted
FROM clients
class UpdateContactsViewToVersion2 < ActiveRecord::Migration
def change
update_view :contacts, version: 2, revert_to_version: 1
end
end