2011-04-04 65 views
1

Rails的多態關聯錯誤

class Store < ActiveRecord::Base 
    belongs_to :user 
    has_many :products, :as => :imageable 
end 

class User < ActiveRecord::Base 
    has_one :store 
    has_many :products, :as => imageable 
end 

class Product < ActiveRecord::Base 
    belongs_to :imageable, :polymorphic => true 
end 

和我進行遷移:

class AddImageableToProducts < ActiveRecord::Migration 
    def self.up 
    change_table :products do |t| 
     t.references :imageable, :polymorphic => true 
    end 
    end 

    def self.down 
    remove_column :products, :imageable 
    end 
end 

當我嘗試運行我的應用程序我得到:未定義的局部變量或方法'成像' 和我不不知道我錯過了什麼。我很感激,如果有人可以幫助。謝謝

回答

0

我同意@kishie,因爲產品是多態的,它可以與更多的相關與一個模型相比,您需要在產品表中有兩列來標識與實例關聯的模型。和。

我相信你在你的lib文件夾中有這個。

lib/imageable.rb 
module Imageable 
    def self.included(base) 
     base.class_eval do 
      has_many :products, :as => imageable 
     end 
    end 
end 

因爲,我假設你使用Rails 3,lib文件夾的內容不會自動加載。你應該有這個在您的application.rb

config.autoload_paths += %W(#{config.root}/lib) 

添加字段,遷移,編輯application.rb中和你設置與多態關聯。

+0

謝謝山姆。我使用的是Rails 3,但我不知道需要單獨的lib文件或在application.rb中有config.autoload_paths。我閱讀了rubyonrails.org上的多態關聯,並沒有提到任何這些。你知道我在哪裏可以讀到你對我的建議嗎?謝謝你一堆 – railslearner 2011-04-04 17:40:05

+0

我嘗試了你提到的一切,而且我仍然遇到同樣的錯誤。多態協會是應該實現這麼複雜嗎? – railslearner 2011-04-04 17:50:59

+0

試試這個:http://railscasts.com/episodes/154-polymorphic-association – 2011-04-05 06:14:29

0

在我看來,在你的情況下,你應該使用像「產品」的東西。 但是如果你無論如何要使用這個名字,你應該添加到您的產品以下字段表thwe:

imageable_id整數和imageable_type爲字符串。

還有一件事,在你遷移你可以使用這個

def self.up 
add_column :table_name, :field_name, :field_type 
end 

def self.down 
remove_column :table_name, :field_name 
end 

,而不是你的代碼=)

+0

謝謝Kishie。我試圖用產品做到這一點,並將其改爲可成像,看看它是否會產生影響。由於我是新來的鐵軌我只是儘量保持儘可能接近指南:)感謝您的建議 – railslearner 2011-04-04 17:41:01