2014-12-23 62 views
0

我非常喜歡,我認爲我對當前的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. 

我意識到這是一種愚蠢的問題,但我沒有發現任何教程,教我應該如何添加此數據到我的桌子。我將不勝感激您的幫助

回答

1

這是值的數組:

data[:new] = [tweet.id,@hashtag.id] 

之前另一個變量(或數據結構)內移動的東西,嘗試是明確的第一個。

@hashrel = Hashtagrelation.new(tweet_id: tweet.id, hashtag_id: @hashtag.id) 

其餘的代碼看起來不錯,我想你已經明白了。

+1

是的,就是這樣:P非常感謝你:D –