Created
October 15, 2011 03:29
-
-
Save renz45/1288985 to your computer and use it in GitHub Desktop.
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
# == Schema Information | |
# | |
# Table name: posts | |
# | |
# id :integer not null, primary key | |
# title :string(255) | |
# content :text | |
# user_id :integer | |
# slug :string(255) | |
# created_at :datetime | |
# updated_at :datetime | |
# categories_count :integer | |
# tags_count :integer | |
# comments_count :integer | |
# status_id :integer | |
# | |
class Post < ActiveRecord::Base | |
before_save :update_slug | |
after_initialize :init_many_to_many_counters | |
belongs_to :user | |
has_many :category_posts | |
has_many :categories, through: :category_posts | |
has_many :post_tags | |
has_many :tags, through: :post_tags | |
has_many :comments, dependent: :destroy | |
belongs_to :post_status, foreign_key: :status_id, counter_cache: :posts_count | |
# setup validations | |
validates :title, presence: true | |
validates :user_id, presence: true | |
def init_many_to_many_counters | |
#setup_many_to_many_counts(:categories, :tags) | |
end | |
#self.reflections.map {|i| next unless i[1].through_reflection; i[0] }.compact | |
# def categories_with_count=(categories) | |
# has_many_items = self.categories.dup | |
# self.categories = categories | |
# has_many_update_counters(:categories, :posts_count, has_many_items) | |
# end | |
# def tags_with_count=(tags) | |
# has_many_items = self.tags.dup | |
# self.tags = tags | |
# has_many_update_counters(:tags, :posts_count, has_many_items) | |
# end | |
def update_slug | |
binding.pry | |
self.slug ||= Post.clean_url(self.title) unless self.title.nil? | |
#update_counters | |
end | |
def self.clean_url(url) | |
clean = url.gsub(" ", "-") | |
clean = clean.gsub(/[?\\\.\,\<\>\!\@\#\$\%\^\&\*\(\)]/, "") | |
clean | |
end | |
private | |
def setup_many_to_many_counts(args = {}) | |
args.each do |k,v| | |
v = "#{self.class.downcase.pluralize}_count" if v.nil? | |
self.class_eval{ | |
define_method "#{k}_with_count=" do |items| | |
has_many_items = self.method(k).call().dup | |
self.method(k).call(items) | |
has_many_update_counters(k, v, has_many_items) | |
end | |
} | |
end | |
end | |
def has_many_update_counters(table,col,items) | |
self_items = self.method(table).call() | |
binding.pry | |
unless(items == self_items) | |
model = table.to_s.singularize.camelize.constantize | |
decrement_arr = items - self_items | |
increment_arr = self_items - items | |
model.decrement_counter(col, decrement_arr.map{|d| d.id}) | |
model.increment_counter(col, increment_arr.map{|i| i.id}) | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment