2012-02-01 57 views
0

單面唯一我有三種模式:HAS_MANY通過 - 在數據庫

class Feed < ActiveRecord::Base 
    has_many :filters, :dependent => :destroy 
    has_many :keywords, :through => :filters, :uniq => true 
end 

class Filter < ActiveRecord::Base 
    belongs_to :feed 
    belongs_to :keyword 

    validates_uniqueness_of :keyword_id, :scope => :feed_id 
end 

class Keyword < ActiveRecord::Base 
    has_many :filters, :dependent => :destroy 
    has_many :feeds, :through => :filters 
end 

我想是在數據庫的關鍵字只有唯一條目。例如,如果兩個提要都有關鍵字'hello',則應該有兩個指向同一個關鍵字的過濾器(每個提要一個)。

我遇到麻煩的是控制器代碼。也許我正在尋找一個太簡單的解決方案,但我認爲必須有一個簡單的方法來做到這一點。這是我在我的創建行動至今:

def create 
    @feed = Feed.find(params[:feed_id]) 
    @keyword = @feed.keywords.create(params[:keyword]) 


    redirect_to feed_keywords_path(@feed), notice: 'Keyword added successfully.' 
end 

有了這個控制器代碼,在前面的例子將導致數據庫中,每一個進料/過濾重複的關鍵字。有沒有一個直接的解決方案,或者我需要事先做一個檢查,看看是否已經有一個關鍵字,在這種情況下只是創建過濾器?

回答

1

使用動態取景器find_or_create_by

def create 
    @feed = Feed.find(params[:feed_id]) 
    @keyword = Keyword.find_or_create_by_keyword(params[:keyword]) # I assume here that you have a column 'keyword' in your 'keywords' table 
    @feed.keywords << @keyword unless @feed.keywords.all.include?(@keyword) 

    redirect_to feed_keywords_path(@feed), notice: 'Keyword added successfully.' 
end 
+0

這樣做的問題,據我可以告訴的是,儘管沒有創建任何重複的關鍵字,你還沒有創建需要被過濾對象創建用於將關鍵字加入數據庫中的提要。 除非這就是'<<'所做的。但我認爲這只是將它推到陣列的末尾。 – dchapman 2012-02-01 20:46:31

+0

我從來沒有嘗試過,但根據http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association,它應該創建連接模型。你有沒有嘗試過 ? – Baldrick 2012-02-02 07:45:03

+0

雖然我不得不作出兩個小小的改變,但確實奏效!非常感謝。這是比我想象的更優雅的解決方案。下面是我不得不改變什麼:? '@feed.keywords << @Keyword除非@ feed.keywords.all.include(@關鍵字)' 的。所有被需要讓一個數組,而不是關係(Rails 3),並且據我所知,包含的不是數組中的類方法,但包括?作品 – dchapman 2012-02-02 16:32:10