我非常喜欢,我认为我对当前的ruby知识进行了超越,但我不想放弃。 我目前有一个可以发布的推文,并且人们可以关注其他人,这要归功于https://www.railstutorial.org/book/。我确实希望将标签添加到本教程高音扬声器中。为了做到这一点,我创建了2个表格,因为tweet和hashtag是多对多的关系。这些表是:在ruby中将数据添加到数据库中
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
这是额外的表,你需要保持鸣叫和哈希标签的键。和其他表是包括hashtag表,其中我的ID,我把下面的relathipships的hastag
class CreateHashtags < ActiveRecord::Migration
def change
create_table :hashtags do |t|
t.string :name
t.timestamps null: false
end
end
end
在车型的名称:
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
在鸣叫时submited我保存它如果它被保存了,我想看看它是否有标签,如果是,我想在Hashtagrelations和Hashtags表中添加必要的数据。 我尝试这这样做:
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
这是不正确的做法。我试图添加newhash和数据,因为如果我只是做标记那里我会得到
When assigning attributes, you must pass a hash as an argument.
我意识到这是一种愚蠢的问题,但我没有发现任何教程,教我应该如何添加此数据到我的桌子。我将不胜感激您的帮助
是的,就是这样:P非常感谢你:D –