2011-04-04 81 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