I am in quite the pickle , I think I overreach with my current ruby knowledge but I don't want to give up. I currently have a tweeter that can post and people can follow other people thanks to https://www.railstutorial.org/book/ . I do want to add hashtags to this tutorial tweeter. In order to do I created 2 tables since tweet and hashtag is a many to many relationship . The tables are :
class CreateHashrelations < ActiveRecord::Migration
def change
create_table :hashrelations do |t|
t.integer :tweet_id
t.integer :hashtag_id
t.timestamps null: false
end
add_index :hashrelations, [:tweet_id, :hashtag_id], unique: true
end
end
which is the extra table you need to keep the keys of the tweet and hashtag . And the other table is the hashtag table where I have the id and the name of the hastag
class CreateHashtags < ActiveRecord::Migration
def change
create_table :hashtags do |t|
t.string :name
t.timestamps null: false
end
end
end
In the models I put the following relathipships:
class Hashtag < ActiveRecord::Base
has_many :hashtagrelations, dependent: :destroy
has_many :tweets, through: :hashtagrelations
validates :name, presence: true
end
class Hashrelation < ActiveRecord::Base
belongs_to :tweet
belongs_to :hashtag
validates :tweet_id, presence: true
validates :hashtag_id, presence: true
end
class Tweet < ActiveRecord::Base
.....
has_many :hashtagrelations, dependent: :destroy
has_many :hashtags, through: :hashtagrelations
....
end
When a tweet is submited I save it and if it is saved I want to see if it has hashtags and if it does I want to add the necessary data in the Hashtagrelations and Hashtags tables. I try to do this this way :
class TweetsController < ApplicationController
......
def create
@tweet = current_user.tweets.build(tweet_params)
if @tweet.save
add_hashtags(@tweet)
flash[:success] = "Tweet created!"
redirect_to root_url
else
@feed_items = []
render 'static_pages/home'
end
end
......
private
........
def add_hashtags(tweet)
tweet.content.scan(/(?:\s|^)(?:#(?!(?:\d+|\w+?_|_\w+?)(?:\s|$)))(\w+)(?=\s|$)/){ |tag|
newhash[:new] = tag
@hashtag = Hashtag.new(new_hash[:new])
@hashtag.save
data[:new] = [tweet.id,@hashtag.id]
@hashrel = Hashtagrel.new(data[:new])
@hashrel.save
}
end
end
Which is not the right way. I tried to add the newhash and data because if I only did tag there I would get
When assigning attributes, you must pass a hash as an argument.
I realise that this is kind of a silly question but I have found no tutorial that teaches me how should I add this data to my tables. I would be grateful for your help