zoukankan      html  css  js  c++  java
  • rails 多态

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

  • 相关阅读:
    问题.NET--win7 IIS唯一密钥属性“VALUE”设置为“DEFAULT.ASPX”时,无法添加类型为“add”的重复集合
    java传统web项目添加maven管理jar包,log4j无法正常输出日志
    TortoiseSVN设置Beyond Compare为版本比较、差异合并工具
    Win10以管理员身份启动cmd.exe
    SprinMVC中文件上传只在内存保留一份拷贝
    maven项目运行报错invalid LOC header (bad signature)
    c#编写windows服务在开机是OnStart启动超时
    centos安装mysql
    CENTOS7配置静态IP
    @__CheckForDebuggerJustMyCode@4
  • 原文地址:https://www.cnblogs.com/lizhenjiang/p/7111458.html
Copyright © 2011-2022 走看看