美文网首页ruby on rails
术-机制:使用rails中间表的注意事项

术-机制:使用rails中间表的注意事项

作者: 稻草人_b788 | 来源:发表于2019-07-08 19:19 被阅读0次

一、rails中的中间表

在表示多对多关系时,我们经常会借助中间表来表示这一关系。

(一)案例1:用户与评论

当我们表达购物车和商品间的关系时,会用到中间表,这个中间表是第三张表。
一个购物车中可以有多种商品,而一种商品也可以放到多个购物车中。此时我们可以建立两者间的多对多关系:

class CartItem < ApplicationRecord
#中间表,可理解为购物车中的栏位
belongs_to :cart
belongs_to :product
end
class Cart < ApplicationRecord
#购物车
has_many :cart_items
has_many :products,through: :cart_items
end

class Product < ApplicationRecord
#商品
has_many :cart_items
has_many :carts,through: :cart_items
end

(二)案例2:用户关注

当我们在表述用户关注关系时,也会借助中间表,有所不同的是"我关注的"和"关注我的"都在同一张users表,所以这里只有两张表的关系:

class User < ApplicationRecord
#表述我关注的人
has_many :active_relationships,class_name: "Relationship",foreign_key: "follower_id"

has_many :following,through: :active_relationships,source: :followed


#表述关注我的人
has_many :passive_relationships,class_name: "Relationship",foreign_key: "followed_id"

has_many :followers,through: :passive_relationships,source: :follower
end
class Relationship < ApplicationRecord
belongs_to :follower,class_name: "User"

belongs_to :followed,class_name: "User"
end

需要注意的是:
这里之所以要把relationships划分为active_relationships和passive_relationships,是因为在同一个model中如果根据follower_id和followed_id去分别查找“我关注的人”和“关注我的人”,都使用了相同的关系名relationships,那么后面一个定义会覆盖前面一个,即follower_id去找用户的那个relationships将会始终返回空数组而找不到正确的数据。例如:

has_many :relationships,foreign_key: "follower_id" #被下面一个关系覆盖,这个关系查找到的资料将始终为空数组

has_many :relationships,foreign_key: "followed_id"

因此这里需要区分这两种查找关系分别为active_relationships和passive_relationships。

相关文章

  • 术-机制:使用rails中间表的注意事项

    一、rails中的中间表 在表示多对多关系时,我们经常会借助中间表来表示这一关系。 (一)案例1:用户与评论 当我...

  • Active Record的设计

    自动加载机制 Active Record是Rails的ORM功能实现。上面代码使用了ActiveSupport::...

  • jupyter-mongo

    使用mongo 进去 使用那些db,collection 创建新表 复制新表复制的时候很慢 注意事项! jupyt...

  • 术-机制:rails中的around回调

    一、around回调 在rails中除了before回调和after回调,还有一种around回调比如around...

  • rails 方法和对象

    rails 路由(rails 通过路由配置表来转发url动作) 路由表的功能: 接收识别http 请求 处理url...

  • NodeJS中间件机制学习

    理解NodeJS中间件机制核心代码的实现,加深对中间件机制的理解,有助于更好的使用和编写中间件。 目录 中间件概念...

  • 【原创】NodeJS中间件机制探索和实现

    理解NodeJS中间件机制核心代码的实现,加深对中间件机制的理解,有助于更好的使用和编写中间件。 目录 中间件概念...

  • NodeJS 中间件机制

    理解 Node.js 中间件机制核心代码的实现,加深对中间件机制的理解,有助于更好的使用和编写中间件。 一、中间件...

  • koa服务器搭建基础

    之前我一直使用rails搭建网站。rails与koa的基本理念很相似,都是基于中间件提供一层层的服务。所不同的是,...

  • rails学习

    使用 $gem install rails 安装rails (具体前置配置看ruby配置环境) rails安装...

网友评论

    本文标题:术-机制:使用rails中间表的注意事项

    本文链接:https://www.haomeiwen.com/subject/zcoahctx.html