在 Rails 5.1 之後的版本,belongs_to 关联的 model 预设改成必填了,也就是一定要有。透过 optional => true 可以允许 event 没有 category 的情况。
class Event < ApplicationRecord
belongs_to :category, :optional => true
end
如果你是从旧版 Rails 升级上来,可以在 config/application.rb 中加入 Rails.application.config.active_record.belongs_to_required_by_default = false 改回旧版的预设行为。
class_name
可以变更关联的类别名称,例如:
class Event < ApplicationRecord
belongs_to :manager, :class_name => "User" # 预设的外部键叫做 manager_id
end
foreign_key
可以变更Foreign Key的栏位名称,例如改成user_id :
class Event < ApplicationRecord
belongs_to :manager, :class_name => "User", :foreign_key => "user_id"
end
touch
这会在修改时,也顺道修改关联资料的updated_at时间:
class Attendee < ApplicationRecord
belongs_to :event, :touch => true
end
counter_cache
针对关联作计数的快取,假设Event身上有attendees_count这个栏位,那麽:
class Attendee < ApplicationRecord
belongs_to :event, :counter_cache => true
end
这样ActiveRecord就会自动更新attendees_count的数字。
[Rails 实战圣经] https://ihower.tw/rails/activerecord-relationships.html
>>: .NET Core第5天_IWebHostEnvironment 的用途是舍麽?
以下内容皆参考 Backtrader 官网 昨天使用了 backtrader 将 shioaji 的...
Livewire 大致上功能都已经介绍完了,接下来就是一些常用的实作时间啦!!今天要来做最常会遇到的...
资料分析根据目的和场景的不同,通常会有着不同适合的呈现方式,例如 如果是在学术单位 会偏好比较明确的...
首先从Moveit官方的Tutorial开始。使用C++撰写机器手臂的控制。教材依据Move Gro...
前几篇介绍了 WebRTC 是如何连线的,今天我们要开始在浏览器上使用 WebRTC 的 API。 ...