Rails多态关联错误

时间:2011-04-04 06:37:09

标签: ruby-on-rails polymorphic-associations

我有

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

当我尝试运行我的应用程序时,我得到:未定义的局部变量或方法`imageable' 而且我不知道我错过了什么。如果有人可以提供帮助,我会很感激。感谢

2 个答案:

答案 0 :(得分:0)

在我看来,在你的情况下,你应该使用类似“可生产”的东西。 但是,如果您仍然想使用此名称,则应在以下字段中添加到您的产品表中:

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

而不是你的代码=)

答案 1 :(得分:0)

我同意@kishie,因为Product是Polymorphic,它可以与多个模型相关联,您需要在products表中有两列来标识这个实例所关联的模型。 imageable_idimageable_type

我相信你在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,并设置多态关联。