2011-01-11 92 views
2

我試圖建立一個數據庫的URL(鏈接)。我有一個分類模型,它有許多鏈接。混合has_one和has_and_belongs_to_many關聯

這是我跑遷移:

class CreateLinksCategories < ActiveRecord::Migration 
    def self.up 
    create_table :links_categories, :id => false do |t| 
    t.references :link 
    t.references :category 
    end 
end 

def self.down 
    drop_table :links_categories 
    end 
end 

這裏的鏈接模式:

class Link < ActiveRecord::Base 
    validates :path, :presence => true, :format => { :with => /^(#{URI::regexp(%w(http  
                https))})$|^$/ } 
    validates :name, :presence => true 

    has_one :category 
end 

這裏的類型模型

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :links 
end 

而這裏的錯誤控制檯踢來踢去,當我試圖在第一鏈路與第一類相關聯:

>>link = Link.first 
=> #<Link id: 1, path: "http://www.yahoo.com", created_at: "2011-01-10... 
>>category = Category.first 
=> #<category id : 1, name: "News Site", created_at: "2011-01-11... 
>>link.category << category 
=> ActiveRecord::StatementInvalid: SQLite3::Exception: no such column :   
    categories.link_id: 

是我的錯協會還是我失去了在數據庫中的東西嗎?我期望它找到links_categories表。任何幫助表示讚賞。

回答

1

爲什麼你在這裏使用HABTM?只需在鏈接上輸入belongs_to :category,然後在類別上輸入has_many :links即可。然後在db中,根本不需要連接表,只需要鏈接表上的category_id。

但是,如果您確實需要HABTM,快速瀏覽一下,我注意到的第一件事是您的連接表命名錯誤 - 它應該是按字母順序排列的,categories_links

第二件事是,你不能混合has_one和has_and_belongs_to_many。 HABTM意味着 - A有許多B和A屬於許多B;這種關係意味着相反也必須是真實的 - B有許多A和B屬於許多A.如果鏈接HABTM cateogries,那麼類別必須是HABTM鏈接。

參見http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many

+0

這工作。謝謝! – Thomas 2011-01-11 18:13:21