Skip to content

Commit e8a8c1a

Browse files
committed
PostsController#create should explicitly handle that :post is present & not cause a server error
1 parent a93b782 commit e8a8c1a

3 files changed

Lines changed: 27 additions & 3 deletions

File tree

app/controllers/posts_controller.rb

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,23 @@ def new
3636
end
3737

3838
def create
39+
submitted = params[:post]
40+
41+
unless submitted.present?
42+
flash[:danger] = helpers.i18ns('posts.create_requires_post')
43+
redirect_back fallback_location: root_path
44+
return
45+
end
46+
3947
@parent = Post.where(id: params[:parent]).first
4048
@post_type = if @parent.present? && @parent.post_type.answer_type.present?
4149
@parent.post_type.answer_type
4250
else
43-
PostType.find(params[:post][:post_type_id])
51+
PostType.find(submitted[:post_type_id])
4452
end
4553
@category = if @post_type.has_category
46-
if params[:post][:category_id].present?
47-
Category.find(params[:post][:category_id])
54+
if submitted[:category_id].present?
55+
Category.find(submitted[:category_id])
4856
elsif @parent.present?
4957
@parent.category
5058
end

config/locales/strings/en.posts.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
en:
22
posts:
33
#alert/notice
4+
create_requires_post: >
5+
Can't create a post without content. Please try again later or contact us.
46
category_low_trust_level: >
57
You don't have a high enough trust level to post in the :name category.
68
type_requires_category: >

test/controllers/posts/create_test.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,20 @@ class PostsControllerTest < ActionController::TestCase
3131
assert_redirected_to_sign_in
3232
end
3333

34+
test 'create requires post' do
35+
sign_in users(:standard_user)
36+
37+
post :create, params: {
38+
category: categories(:main).id,
39+
post_type: post_types(:question).id
40+
}
41+
42+
assert_response(:found)
43+
assert_redirected_to root_path
44+
assert_not_nil flash[:danger]
45+
assert_nil assigns(:post)
46+
end
47+
3448
test 'can create help post' do
3549
sign_in users(:moderator)
3650

0 commit comments

Comments
 (0)