-
-
Save tarot/c1e74f0d451aac7e5242 to your computer and use it in GitHub Desktop.
_typeがサブクラスを指すようにしたい。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", ... } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
productsテーブルにtypeカラムはあえてつけてないんだけど付けても同じ。