0

嘗試使用has_and_belongs_to_many關聯時遇到了一個相當令人沮喪的問題。Rails 3.1與自定義foreign_key的HABTM關聯會生成錯誤的連接語句

該場景如下。

我有一個產品,有許多新聞項目關聯,反之亦然。新聞項目可以翻譯成不同的語言,所以爲了跟蹤具有相同內容的新聞(但翻譯成不同的語言) - 我已經添加了news_id新聞。

我的問題是,產品和獨特消息(newsitem.news_id)之間的關聯不在單個消息項目(newsitem.id)之間。

我的模型:

class Product < ActiveRecord::Base 
    has_and_belongs_to_many :newsitems , :association_foreign_key => :news_id 
end 

class Newsitem < ActiveRecord::Base 
    has_and_belongs_to_many :products, :foreign_key => :news_id 
end 

我的遷移如下:

def change 
    create_table :products do |t| 
     t.string :name 
     t.timestamps 
    end 
end 

def change 
    create_table :newsitems do |t| 
     t.string :content 
     t.integer :news_id 
     t.integer :language_id 
     t.timestamps 
    end 
end 

def change 
    create_table :newsitems_products, :id => false do |t| 
     t.integer :news_id 
     t.integer :product_id 
    end 
end 

使用此設置,我得到以下正確的SQL調用時產生:

news = Newsitem.first 
news.products.to_sql 

SQL:

"SELECT `products`.* FROM `products` 
INNER JOIN `newsitems_products` 
ON `products`.`id` = newsitems_products`.`product_id` 
WHERE `newsitems_products`.`news_id` = 1" 

的麻煩開始,當我問與產品相關聯的所有newsitems: 督促= Products.first prod.newsitems.to_sql SQL:

"SELECT `newsitems`.* FROM `newsitems` 
INNER JOIN `newsitems_products` 
ON `newsitems`.`id` = `newsitems_products`.`news_id` 
WHERE `newsitems_products`.`product_id` = 1" 

Eventhough我已經聲明:association_foreign_key =>:news_id on產品和:foreign_key =>:newsitem上的news_id生成「ON newsitemsid「是錯誤的,應該是:

ON `newsitems`.`news_id` = `newsitems_products`.`news_id` 

我希望你們中的一些可以破解這個螺母開放提前

謝謝 - 彼得·派珀

回答

2

我有同樣的問題,我會寫一個類似的例子

1。第一模型:

class Label < ActiveRecord::Base 
has_and_belongs_to_many :spaces 
end 

2.Seco Nd模式:

class Space < ActiveRecord::Base 
has_and_belongs_to_many :labels 
end 

3.遷移:

rails g migration createSpacesLabels 
  1. 編輯遷移:

    class CreateSpacesLabels < ActiveRecord::Migration 
    def up 
        create_table :spaces_labels, :id => false do |t| 
        t.references :space 
        t.references :label 
    end 
    add_index :spaces_labels, [:label_id, :space_id] 
    add_index :spaces_labels, [:space_id, :label_id] 
    end 
    
    def down 
    drop_table :spaces_labels 
    end 
    end 
    
  2. 問題:

    我發現軌搜索錯誤TA ble,它會查找labelsspaces而不是空格標籤,我猜這是因爲模型的名稱。我解決它通過在模型中加入:現在

    has_and_belongs_to_many :labels,:join_table=>'spaces_labels' 
    
    has_and_belongs_to_many :spaces,:join_table=>'spaces_labels' 
    

,你應該能夠執行像@ space.labels或@ label.spaces查詢。 我希望它有幫助。