-
Notifications
You must be signed in to change notification settings - Fork 3
/
cart_tip.rb
97 lines (70 loc) · 2.29 KB
/
cart_tip.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# cart.rb
def total_items
line_items.sum(:quantity)
end
def total_price
line_items.to_a.sum {|item| item.total_price}
end
#line_item.rb
def total_price
product.price * quantity
end
# application_controller.rb
class ApplicationController < ActionController::Base
before_action :authorize
protect_from_forgery
private
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
session[:cart_id] = cart.id
cart
end
def current_user
end
protected
def authorize
unless User.find_by(id: session[:user_id])
redirect_to login_path, notice: "Please log in"
end
end
end
#store_controller.rb
class StoreController < ApplicationController
skip_before_action :authorize
end
# sessions_controller.rb
class SessionsController < ApplicationController
skip_before_action :authorize
end
class LineItemsController < ApplicationController
skip_before_action :authorize, only: :create
end
class OrdersController < ApplicationController
skip_before_action :authorize, only: [:new,:create]
end
#config/application.rb
#开启lib目录,让rails加载lib中的代码.其中的代码(库代码)可以在MVC三个地方共享
config.autoload_paths += %W(#{Rails.root}/lib)
#如果一个库不能满足加载条件,可以使用require机制。比如要加载lib/hello.rb文件,可以在任意MVC三个地方的文件开头,require "hello"。子目录下要加子目录的路径
require "shipping/arimail" # lib/shipping/arimail.rb
Account.transaction do
ac = Account.where(id: id).lock("LOCK IN SHARE MODE").first
ac.balance -= amount if ac.balance > amount
ac.save
end
class Order < ActiveRecord::Base
scope :last_days, ->{ |days| where('updated< ?', days) }
scope :checks, where(pay_type: :check)
end
#使用find_by_sql效率其实是更高的
def add_comment
@article = Article.find(params[:id])
comment = Comment.new(params[:comment])
@article.comments << comment
@article.save
end
#使用签名cookies 这样只能得到自己的cookies,无法通过浏览器修改得到别人的cookies
#关键信息在cookies中保存后要尽可能存数据库,防止cookies丢失或删除