bachpx195 / experience

kiến thức thì vô tận.
1 stars 0 forks source link

EXPERIENCE Rails tricks #24

Closed bachpx195 closed 3 years ago

bachpx195 commented 7 years ago
bachpx195 commented 7 years ago

/model.rb dependent: Destroy xóa phần tử sẽ xóa luôn trong các bảng khác phụ thuộc vào nó.

rails50/depot_f/app/models/cart.rb
class Cart < ApplicationRecord
      **has_many :line_items, dependent: :destroy**
end
bachpx195 commented 7 years ago

Object's cycle

rails50/depot_f/app/models/product.rb class Product < ApplicationRecord ➤ has_many :line_items ➤ _before_destroy :ensure_not_referenced_by_any_lineitem

...

➤ private ➤ # ensure that there are no line items referencing this product ➤ def ensure_not_referenced_by_any_line_item ➤ unless line_items.empty? ➤ errors.add(:base, 'Line Items present') ➤ throw :abort ➤ end ➤ end end

bachpx195 commented 7 years ago

Error Handler

## ActiveRecord::RecordNotFound

class CartsController < ApplicationController
before_action :set_cart, only: [:show, :edit, :update, :destroy]
➤ rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart
# GET /carts
# ...
private
# ...
➤ def invalid_cart
➤ logger.error "Attempt to access invalid cart #{params[:id]}"
➤ redirect_to store_index_url, notice: 'Invalid cart'
➤ end

Trả về giá trị lỗi khi không tìm thấy record bằng flash.

bachpx195 commented 7 years ago

Passing argument to '.js.erb' template

format.js { render :layout => false, :locals => { @current_item => @line_item } }