RailsのPolymorphicでhas_oneするヘ(^o^)ノ

Polymorphicのhas_one関連を書いてる記事が少なかったので

ついでにPolymorphicのおさらいしておく

環境

モデルをgeneratorでつくる

# zshなんでエスケープしてますです
$ bin/rails g model picture imageable:references\{polymorphic\}
$ bin/rake db:migrate
class Picture < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
end

できました

has_many

まずは has_manyから

関連モデルをgeneratorでつくる

$ bin/rails g model employee name
$ bin/rake db:migrate

モデルにhas_manyを設定

class Employee < ActiveRecord::Base
  has_many :pictures, as: :imageable
end

コンソールで確認してみる

$ bin/rails c -s
> employee.imageable.create
=> #<Employee id: 1, name: nil, created_at: "2016-04-23 15:51:52", updated_at: "2016-04-23 15:51:52">
> employee.pictures.create
=> #<Picture id: 1, imageable_id: 1, imageable_type: "Employee", created_at: "2016-04-23 15:52:17", updated_at: "2016-04-23 15:52:17">

できました

has_one

さて、問題のhas_one

関連モデルをgeneratorでつくる

$ bin/rails g model product name
$ bin/rake db:migrate

モデルにhas_oneを設定

class Product < ActiveRecord::Base
  has_one :picture, as: :imageable
end

コンソールで確認してみる

$ bin/rails c -s
> product = Product.create
=> #<Product id: 1, name: nil, created_at: "2016-04-23 15:58:33", updated_at: "2016-04-23 15:58:33">
> product.picture.create
NoMethodError: undefined method `create' for nil:NilClass

怒られました

> product.create_picture
=> #<Picture id: 1, imageable_id: 1, imageable_type: "Product", created_at: "2016-04-23 16:10:46", updated_at: "2016-04-23 16:10:46">

できました

Polymorphicでhas_oneするケースが少ないかも( ˘ω˘)

そもそも、Polymorphic関係なかったんや、、

Happy Hacking٩( ‘ω’ )و

参考

ActiveRecord::Associations::ClassMethods