zoukankan      html  css  js  c++  java
  • rails 中model之间的 association (:inverse_of)

    class Customer < ActiveRecord::Base

      has_many :orders

    end

    class Order < ActiveRecord::Base

      belongs_to :customer

    end

    如上代码两个model在做如下查询的时候:

    c = Customer.first

    o = c.orders.first

    c.first_name == o.customer.first_name # true

    c.first_name = "other name"

    c.first_name == o.customer.first_name # false

    这是因为c 和 o.customer 在内存中两个对象对应的同一个数据

    当在model中添加  :inverse_of 的时候就会出现这种情况:

    class Customer < ActiveRecord::Base

      has_many :orders, inverse_of: :customer

    end

    class Order < ActiveRecord::Base

      belongs_to :customer, inverse_of: :orders

    end

    ####

    o = c.orders.first

    c.first_name == o.customer.first_name # true

    c.first_name = "other name"

    c.first_name == o.customer.first_name # true

    当添加了inverse_of ,只会加载一个customer对象

    在用inverse_of的时候是有限制的:

    有这些条件:through  :polymorphic :as 的时候,因为有belongs_to和has_many, inverse_of 这个会被忽略!

    当有这些条件的时候

    :conditions
    :through
    :polymorphic
    :foreign_key 关联不会自动逆转!

  • 相关阅读:
    CKeditor3.6.2 配置与精简
    CKEditor与CKFinder整合并实现文件上传功能
    实体关联关系映射:
    status pending状态
    wx:for
    小程序
    获取指定控件的值
    报表
    dataGridView 设置
    SQLite 的使用
  • 原文地址:https://www.cnblogs.com/perish/p/3812301.html
Copyright © 2011-2022 走看看