Created
November 17, 2015 08:28
-
-
Save olistik/7096fc58c08c983817eb to your computer and use it in GitHub Desktop.
How to implement (Discussion N:M Tag) with ActiveRecord
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
class Discussion < ActiveRecord::Base | |
has_and_belongs_to_many :tags | |
def self.my_scope | |
# TODO: replace me with something meaningful | |
where("discussions.id < 10") | |
end | |
def self.tags_count | |
joins(:tags). | |
group("tags.id"). | |
order("count_all desc"). | |
count | |
end | |
end |
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
discussions = Discussion.my_scope | |
tags_with_count = TagsForDiscussions.perform(discussions: discussions) |
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
class CreateDiscussions < ActiveRecord::Migration | |
def change | |
create_table :discussions do |t| | |
t.string :name | |
t.timestamps null: false | |
end | |
end | |
end |
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
20.times {|index| Discussion.create name: "discussion_#{index}"} | |
10.times {|index| Tag.create name: "tag_#{index}"} | |
Discussion.all.sample(10).each do |discussion| | |
discussion.tag_ids = Tag.all.to_a.sample(5).map(&:id) | |
end |
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
class Tag < ActiveRecord::Base | |
has_and_belongs_to_many :discussions | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment