forked from xdite/rails-101
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chapter-04.txt
82 lines (55 loc) · 1.39 KB
/
chapter-04.txt
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
# 練習作業 4 - User 可以加入、退出社團
### 作業目標
* user 可以在 group 頁面加入社團 / 退出社團
* user 必須要是這個社團的成員才能發表文章
### 本章練習主題
* has_many_belongs_to
* custom routes
~~~~~~~~~
class PostsController < ApplicationController
before_action :find_group
before_action :login_required, :only => [:new, :create, :edit,:update,:destroy]
before_action :member_required, :only => [:new, :create ]
def new
@post = @group.posts.build
end
def create
@post = @group.posts.new(post_params)
@post.author = current_user
if @post.save
redirect_to group_path(@group)
else
render :new
end
end
def edit
@post = current_user.posts.find(params[:id])
end
def update
@post = current_user.posts.find(params[:id])
if @post.update(post_params)
redirect_to group_path(@group)
else
render :edit
end
end
def destroy
@post = current_user.posts.find(params[:id])
@post.destroy
redirect_to group_path(@group)
end
private
def post_params
params.require(:post).permit(:content)
end
def find_group
@group = Group.find(params[:group_id])
end
def member_required
if !current_user.is_member_of?(@group)
flash[:warning] = " You are not member of this group!"
redirect_to group_path(@group)
end
end
end
~~~~~~~~~