Skip to content

Instantly share code, notes, and snippets.

@tarot
Last active October 12, 2015 00:14
Show Gist options
  • Save tarot/c1e74f0d451aac7e5242 to your computer and use it in GitHub Desktop.
Save tarot/c1e74f0d451aac7e5242 to your computer and use it in GitHub Desktop.
_typeがサブクラスを指すようにしたい。
class Picture < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
end
class Product < ActiveRecord::Base
end
class PublicProduct < Product
has_one :picture, as: :imageable
end
class PrivateProduct < Product
has_one :picture, as: :imageable
end
PublicProduct.create.build_picture #=> { ..., imageable_type: "Product", ... }
class Migration < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :name
t.boolean :published
t.timestamps null: false
end
create_table :pictures do |t|
t.string :url
t.integer :imageable_id
t.string :imageable_type
t.timestamps null: false
end
add_index :pictures, [:imageable_id, :imageable_type]
end
end
@tarot
Copy link
Author

tarot commented Oct 12, 2015

productsテーブルにtypeカラムはあえてつけてないんだけど付けても同じ。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment