rails 多态

时间:2023-12-19 18:51:08

rails 多态

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 10.0px Monaco; color: #f4f4f4; background-color: rgba(0, 0, 0, 0.85) }
span.s1 { }

rails g model employee name:string

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 10.0px Monaco; color: #f4f4f4; background-color: rgba(0, 0, 0, 0.85) }
span.s1 { }

rails g model product name:string

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 10.0px Monaco; color: #f4f4f4; background-color: rgba(0, 0, 0, 0.85) }
span.s1 { }

rails g model picture name:string imageable_id:integer  imageable_type:string

class Employee < ApplicationRecord
  has_many :pictures, :as => :imageable
end

class Product < ApplicationRecord
  has_many :pictures, :as => :imageable
end

class Picture < ApplicationRecord
  belongs_to :imageable, :polymorphic => true
end

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 10.0px Monaco; color: #f4f4f4; background-color: rgba(0, 0, 0, 0.85) }
p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 10.0px Monaco; color: #34bbc8; background-color: rgba(0, 0, 0, 0.85) }
p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 10.0px Monaco; color: #5230e1; background-color: rgba(0, 0, 0, 0.85) }
span.s1 { }
span.s2 { color: #f4f4f4 }
span.s3 { color: #d53bd3 }
span.s4 { color: #34bc26 }
span.s5 { color: #34bbc8 }

irb(main):001:0> product = Product.create name: "iphone"

(0.1ms)  begin transaction

SQL (1.1ms)  INSERT INTO "products" ("name", "created_at", "updated_at") VALUES (?, ?, ?)  [["name", "iphone"], ["created_at", "2017-07-03 07:26:45.164785"], ["updated_at", "2017-07-03 07:26:45.164785"]]

(0.7ms)  commit transaction

=> #<Product id: 1, name: "iphone", created_at: "2017-07-03 07:26:45", updated_at: "2017-07-03 07:26:45">

irb(main):002:0> picture = product.pictures.create name: 'pic1'

(0.1ms)  begin transaction

Product Load (0.2ms)  SELECT  "products".* FROM "products" WHERE "products"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]

SQL (0.7ms)  INSERT INTO "pictures" ("name", "imageable_id", "imageable_type", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["name", "pic1"], ["imageable_id", 1], ["imageable_type", "Product"], ["created_at", "2017-07-03 07:27:47.046831"], ["updated_at", "2017-07-03 07:27:47.046831"]]

(0.7ms)  commit transaction

=> #<Picture id: 1, name: "pic1", imageable_id: 1, imageable_type: "Product", created_at: "2017-07-03 07:27:47", updated_at: "2017-07-03 07:27:47">

irb(main):003:0> picture

=> #<Picture id: 1, name: "pic1", imageable_id: 1, imageable_type: "Product", created_at: "2017-07-03 07:27:47", updated_at: "2017-07-03 07:27:47">