rails 多态

本文介绍了一个使用Ruby on Rails实现的模型关联案例,包括Employee、Product和Picture三个模型之间的多态关联。具体展示了如何创建Product实例并为其关联Picture,以及如何查询这些关联的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

rails g model employee name:string

 

rails g model product name:string

 

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

 

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">

 

转载于:https://www.cnblogs.com/lizhenjiang/p/7111458.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值