Skip to content

Instantly share code, notes, and snippets.

@MichaelCPell
Created September 10, 2014 03:44
Show Gist options
  • Save MichaelCPell/8679b54d306ef56cbda2 to your computer and use it in GitHub Desktop.
Save MichaelCPell/8679b54d306ef56cbda2 to your computer and use it in GitHub Desktop.
Wiki model with AR optimizations
class Wiki < ActiveRecord::Base
has_many :collabs, dependent: :destroy
has_many :users, through: :collabs
has_one :owner_collab,
-> {where("owner = ?", true)},
class_name: "Collab"
has_one :owner, through: :owner_collab, source: :user
scope :grouped_collabs, -> {
joins(:collabs).group("collabs.wiki_id")
}
scope :by_user_collabs, -> (id){
Wiki.joins(:collabs).where("collabs.user_id = ?",id).where("collabs.owner = ?", false)
}
scope :by_user_wikis, -> (id){
Wiki.joins(:collabs).where("collabs.user_id = ?", id).where("collabs.owner = ?", true)
}
def self.create_wiki_seed(user, title, public = true)
newwiki = Wiki.new(
title: title,
body: "This is a #{title} article.",
public: public
)
newwiki.save
newcollab = Collab.new(
user_id: user.id,
wiki_id: newwiki.id,
owner: true
)
newcollab.save
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment