嘗試使用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 newsitems
。 id
「是錯誤的,應該是:
ON `newsitems`.`news_id` = `newsitems_products`.`news_id`
我希望你們中的一些可以破解這個螺母開放提前
謝謝 - 彼得·派珀