12月17日周日 form_for的部分理解。belongs_to的部分理解
1.lean guide:helper method
query ,✅🍅🍅🍅🍅
2.完成2周作业,并回顾一下(25分钟)✅,🍅🍅
3.再做一遍前两周的 (选择)至少50分钟
4.回顾日记,写周总结。
5.看了guide:belongs_to ✅,🍅
form_for(record, options = {}, &block)
可以传递string,symbol, model object.
1.select. 创建选择标签
select(object, method, choices = nil, options = {}, html_options = {}, &block)
2. url: 表格被提交的位置
3.submit(value = nil, options = {})
解释:增加一个提交按钮,如果没有指定value,会根据object是否是一个新的资源来创建对应的label.
不明白:
@cart_item.product.quantity :返回对应商品的属性quantity的值,即商品库存。
详解:因为CartItim belongs_to :product, 所以CartItem自动获得了5个设计关联的method.本案例用到的是association,即product. @cart_item.product返回关联的产品(product)的object。
引申:association=(associate)的意思。
这里@cart_item.product = @product // 把某一具体product的主键赋予@cart_item的product_id外键
引申2:option的选项,
foreign_key:可以在声明关联的时候,直接设定外键,见下例子
class_name: 真实的父model的名字是patron,author只是其中的一个列
class Book < ApplicationRecord belongs_to :author , class_name: "Patron" , foreign_key: "patron_id" end |
引申3:Scopes for belongs_to ,可以客制化query,通过加一个scope。-> {...}
where,includes等。
where: This method lets you sepcify the conditions that the associated object must meet.
class
book < ApplicationRecord
belongs_to
:author
, -> { where active:
true
}
end
includes: 用于多层关联,效率更高。见(4.1.3.2
引申4: 可以使用associaton.nil? method来判断关联的object是否存在
if @book .author. nil ? @msg = "No author found for this book" end |
引申5:4.1.5 When are Objects Saved? belongs_to 的关联双方在一个新的关联后,双方不自动储存。
cart_item_params[:quantity]: 应该是购物车内的相应商品的数量记录。但不理解写法为何这么写?
helper_method :current_cart 是在application_controller.rb中声明,同时也在这里定义method current_cart.