Created
February 10, 2016 03:31
-
-
Save villanuv/3ecd1e2f397553f60cdd to your computer and use it in GitHub Desktop.
Company Model Thoughts for New Coast
This file contains hidden or 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
# app/models/company.rb | |
class Company < ActiveRecord::Base | |
has_many :taggings | |
has_many :tags, through: :taggings | |
include TagMethods | |
end | |
# app/models/user.rb | |
class User < ActiveRecord::Base | |
has_many :taggings | |
has_many :tags, through: :taggings | |
include TagMethods | |
end | |
# app/models/investor.rb | |
class Investor < ActiveRecord::Base | |
has_many :taggings | |
has_many :tags, through: :taggings | |
include TagMethods | |
end | |
# app/models/concerns/tag_methods.rb | |
module TagMethods | |
extend ActiveSupport::Concern | |
module ClassMethods | |
# tagged_with finds companies tagged with name | |
def self.tagged_with(name) | |
if name | |
Tag.find_by_name!(name).companies | |
else | |
where(nil) | |
end | |
end | |
# tag_counts spits out tag counts | |
def self.tag_counts | |
Tag.select("tags.*, count(taggings.tag_id) as count").joins(:taggings).group("taggings.tag_id") | |
end | |
#tag_list getter retrieves a company's tags and outputs them as a comma-separated string | |
def tag_list | |
tags.map(&:name).join(", ") | |
end | |
# tag_list setter takes in a comma-separated string of tags and assigns them to a company | |
def tag_list=(names) | |
self.tags = names.split(",").map do |n| | |
Tag.where(name: n.strip).first_or_create! | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment