2010-06-15 28 views
6

我正在更新應用程序到Rails 3,我在創建自定義外鍵時遇到問題。我有這樣的事情:belongs_to與自定義class_name不生產正確的外鍵在Rails 3中

class Product < ActiveRecord::Base 
    belongs_to :owner, :class_name => 'User' 
... 
end 

class User < ActiveRecord::Base 
    has_many :products 
... 
end 

class ProductsController < ApplicationController 
    before_filter :authenticate_user! 

    def index 
    @products = current_user.products 
    end 
end 

的觀點:

<%- @products.each do |p| -%> 
    <%= p.created_at %><br /> 
<%- end -%> 

我得到這個錯誤在我的Rails日誌:

Mysql::Error: Unknown column 'products.user_id' in 'where clause': SELECT  `products`.* FROM  `products` WHERE  (`products`.user_id = 1) 

應該看到belongs_to :owner並尋找一個外鍵稱爲owner_id。我什至嘗試明確設置外鍵,這是行不通的。我也檢查了燈塔的一個可能的Rails 3的錯誤,但沒有運氣。

回答

15

您需要指定has_many :products關聯中的外鍵,它不會自動知道它鏡像belongs_to :owner

這應該工作:

class User < ActiveRecord::Base 
    has_many :products, :foreign_key => 'owner_id' 
... 
end

從軌道文檔:

:foreign_key

指定用於關聯的外鍵 。默認 這被推測爲這個 類的名字,小寫字母和「_id」 後綴。因此,一個Person類,使 一個的has_many協會將使用 「爲person_id」作爲默認 :foreign_key ..

+0

這個工作,但我想這是一個有點奇怪,我沒有與我的Rails做2應用程序。不知道它會被認爲是一個錯誤 – Tony 2010-06-15 14:44:24

+0

它應該是相同的Rails 2. :) – elektronaut 2010-06-15 14:51:13

+0

我在我的表上有兩列引用用戶表。你知道我將如何設置參考?我不能像上面建議的那樣說owner_id,因爲我需要Owner和SubmittingUser。謝謝! – skaz 2011-04-17 00:25:03

相關問題