2011-02-14 53 views
0

我只是沒有看到這個代碼有什麼問題。這裏是規格:近視WRT has_many:通過

it "Meta tags should not duplicate for a particular page" do 
    p1 = Page.create!(:title => 'first page', :body_text => 'p1 body text') 
    p2 = Page.create!(:title => 'second page', :body_text => 'p2 body text') 
    p1.add_meta_tag(:content => 'alexa', :description => '100') 
    p2.add_meta_tag(:content => 'alexa', :description => '200') 

    p1.meta_tags.where("content = 'alexa'").should have(1).record 
    p2.meta_tags.where("content = 'alexa'").should have(1).record 
end 

的車型有:

class Page < AR::Base 
    has_many :page_to_meta_tag_maps 
    has_many :meta_tags, :through => :page_to_meta_tag_maps 

    # BONEHEAD PROBLEM PROBABLY HERE... 
    def add_meta_tag(options) 
    @cm = self.meta_tags.where(["content=?", options[:content]]).first 
    @current_meta = @cm || MetaTag.create(options) 
    @current_meta.description = options[:description] 
    self.meta_tags << @current_meta 
    end 
end 

class PageToMetaTagMap < ActiveRecord::Base 
    belongs_to :page 
    belongs_to :meta_tag 
end 

class MetaTag < ActiveRecord::Base 
    attr_accessible :content, :description 

    has_many :page_to_meta_tag_maps 
    has_many :pages, :through => :page_to_meta_tag_maps 
end 

它的失敗規範說有2條記錄,而不是1該日誌顯示了Rails的每次執行INSERT,和@在BONEHEAD PROBLEM區域的cm總是零。我必須從根本上誤解這裏的某些東西。

我喜歡它,當這種情況發生,並有時間壓力:(

回答

0

我改變了檮問題代碼:

def add_meta_tag(options) 
    @current_meta = self.meta_tags.where(["content=?", options[:content]]).first 
    if @current_meta 
    @current_meta.description = options[:description] 
    @current_meta.save 
    else 
    @current_meta = MetaTag.create(options) 
    self.meta_tags << @current_meta 
    end 
end 

解決了問題,我不禁想起,有一個更好的方式...