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 关联不会自动逆转!

  • 相关阅读:
    jquery层级选择器学习笔记
    html 大于号 小于号 空格显示
    MySql存储过程二---变量
    MySql 存储过程一--基本语法及参数介绍
    MySql delimiter
    MySql 关联查询
    MySql 数据库导入导出
    markdown 换行
    WPF 之 MVVM
    对memtester源码分析
  • 原文地址:https://www.cnblogs.com/perish/p/3812301.html
Copyright © 2011-2022 走看看