开发者

Rails Polymorphic Associations Error

开发者 https://www.devze.com 2023-02-22 00:57 出处:网络
I have class Store < ActiveRecord::Base belongs_to :user has_many :products, :as => :imageable end class User < ActiveRecord::Base

I have

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

and I migrated:

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

When I try to run my app I get: undefined local variable or method `imageable' and I don't know what I have missing to have this run. Id appreciate it if somebody could help. Thanks


I agree with @kishie, since Product is Polymorphic, it can be associated with more than one models, you need to have two columns in products table to identify the model this is instance is associated with. imageable_id and imageable_type.

I am sure you have this in you lib folder.

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

Since, I am assuming you're using Rails 3, the contents of lib folder are not loaded automatically. You should have this in your application.rb

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

Add fields, migrate, edit application.rb and you're set with polymorphic associations.


In my opinion, in your case you should use something like "productable". But if you anyway want to use this name you should add to your products table thwe following fields:

imageable_id as integer and imageable_type as string.

And one more thing, in your migration you can use this

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

def self.down
 remove_column :table_name, :field_name
end

instead of your code =)

0

精彩评论

暂无评论...
验证码 换一张
取 消