Skip to content

Instantly share code, notes, and snippets.

@RSijelmass
Created July 3, 2017 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RSijelmass/c86062d6987ee2fe513ab048ffb8f5ca to your computer and use it in GitHub Desktop.
Save RSijelmass/c86062d6987ee2fe513ab048ffb8f5ca to your computer and use it in GitHub Desktop.
Linking Tags Posts many to many
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
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