Reputation: 117
I created a new model called 'hashtags' and a new table in my database
Here's the schema.db
create_table "hashtags", :force => true do |t|
t.string "hashtags"
t.integer "post_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
hashtags.rb
class Hashtags < ActiveRecord::Base
attr_accessible :hashtags, :post_id
end
def create
hashtag_regex = /\b#\w\w+/
@post = current_user.posts.build(params[:post])
@post.hashtags = @post.text.scan(hashtag_regex)
end
Inside the post model, this is what I've added
class Post < ActiveRecord::Base
attr_accessible :content
belongs_to :user
has_many :hashtags, dependent: :destroy
For all posts where there's a hashtag (or could be 2+ hashtags), I want to list them in descending order by date in a new page called '/hashtags'. So this is how I want it to show in view
4/30/2013
#tag3 #tag2 by user2
#tag1 by user5
4/29/2013
#tagz by user10
#tagx #tagy by user3
4/25/2013
#tagz #tagy #tagx by user2
Inside views\static_pages\hashtags.html.erb
I'm trying to create this view, but how could I best go about this?
Upvotes: 0
Views: 855
Reputation: 27
This is how you would dot it in your Model: For
class Post < ApplicationRecord
has_many :hashtags, dependent: :destroy
after_commit :process_hashtags
def process_hashtags
hashtag_regex = (/#\w+/)
text_hashtags = content.to_s.scan(hashtag_regex)
text_hashtags.each do |name|
HashTag.create name: name, address: user.country
end
end
end
Model for # for hashTags
class HashTag < ApplicationRecord
belongs_to :post
end
Upvotes: 0
Reputation: 12429
To save the hash tags you need a before save callback method, and get rid of that logic in the controller.
class Post < ActiveRecord::Base
after_save :process_hashtags
def process_hashtags
hashtag_regex = /\B#\w\w+/
text_hashtags = text.scan(hashtag_regex)
text_hashtags.each do |tag|
hashtags.create name: tag
end
end
end
This callback will iterate through the array of hashtags that it finds in the text, and create a Hashtag
model and associate it with the Post
model.
Let me know if it works, as it might need some adjustments.
Upvotes: 0