Created
July 3, 2017 10:10
-
-
Save RSijelmass/c86062d6987ee2fe513ab048ffb8f5ca to your computer and use it in GitHub Desktop.
Linking Tags Posts many to many
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
1 class Post < ApplicationRecord | |
... | |
... | |
10 def self.find_tag(title, post_id, tag_class = Tag) | |
11 tag = tag_class.find(title) | |
12 | |
13 if tag | |
14 tag_in_db = tag_class.find_by(name: tag) | |
15 | |
16 if tag_in_db | |
17 self.create_posttag(post_id, tag_in_db.id) | |
18 else | |
19 new_tag = tag_class.create(name: tag) | |
20 self.create_posttag(post_id, new_tag.id) | |
21 end | |
22 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
1 class Tag < ApplicationRecord | |
2 has_many :posts_tags | |
3 has_many :posts, through: :posts_tags | |
4 | |
5 def self.find(message) | |
6 message.split(' ').each do |word| | |
7 return word[1...word.length] if word[0] == '#' | |
8 end | |
9 return nil | |
10 end | |
11 end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment