我有這樣的控制器,在那裏我可以創建用戶組,並添加用戶,角色吧:Rails的5:不允許創建行動,如果PARAMS是空
class Strongbolt::UserGroupsController < ApplicationController
# some code...
def create
user_roles #Helper method
respond_to do |format|
if @user_group = Strongbolt::UserGroup.create!(user_group_params)
format.json { head :no_content }
format.js { flash.now[:notice] = "User group #{@user_group.name} created!" }
else
format.json { render json: @user_group.errors.full_messages,
status: :unprocessable_entity }
end
end
end
# some code...
def user_group_params
params.require(:strongbolt_user_group)
.permit(:name, :description, {user_ids: []}, {role_ids: []})
end
如果user_ids
和role_ids
是空的,我需要做一些錯誤或停止創建操作 - 我不需要沒有至少一個用戶和角色的用戶組。請問我該怎麼做?
由於這與Strongbolt gem有關,其中相關的模型在裏面,所以我不能在模型上進行驗證 - 我必須在Controller中進行驗證。此時此功能不存在,所以我必須爲我的項目添加該功能。
到目前爲止,我一直在努力做這個壽相關的東西:
redirect_to 'new' unless params[:user_ids].present?
更新
這裏是我的表的一部分:
<!-- Users tab -->
<div class="tab-pane" id="users">
<div class="i-checks">
<%= f.collection_check_boxes(:user_ids, @users_for_group, :id, :name) do |b| %>
<div class="col-sm-1">
<%= b.check_box %>
</div>
<%= b.label %><br><br>
<% end %>
</div>
</div>
<!-- Roles tab -->
<div class="tab-pane" id="roles">
<div class="i-checks">
<%= f.collection_check_boxes(:role_ids, @roles, :id, :name) do |bb| %>
<div class="col-sm-1">
<%= bb.check_box %>
</div>
<%= bb.label %><br><br>
<% end %>
</div>
</div>
更新2
def create
user_roles #Helper method
respond_to do |format|
unless params[:user_ids].blank? || params[:role_ids].blank?
@user_group = Strongbolt::UserGroup.create!(user_group_params)
format.json { head :no_content }
format.js { flash.now[:notice] = "User group #{@user_group.name} created!" }
else
format.json {
render json: @user_group.errors.full_messages, status: :unprocessable_entity
}
format.js { flash.now[:error] = "User group was not created!" }
end
end
end
在終端我看到這一點:
Started POST "/en/strongbolt/user_groups" for 10.0.2.2 at 2017-06-06 17:51:59 +0000
Processing by Strongbolt::UserGroupsController#create as JS
Parameters: {"utf8"=>"✓", "strongbolt_user_group"=>{"name"=>"Test @Jun6 v2", "description"=>"test", "user_ids"=>["", "5"], "role_ids"=>["", "2"]}, "commit"=>"Create User Group", "locale"=>"en"}
解決方案
首先,它似乎collection_check_boxes
默認包含隱藏值「」,所以,我不得不刪除與這樣的:
<%= f.collection_check_boxes(:role_ids, @roles, :id, :name, include_hidden: false) do |bb| %>
如果不刪除隱藏字段,Rails將不會檢查空的參數,因爲基本上參數是有的。
然後我就能夠實現這一點:
before_action :validate_presence, only: [:create]
def check_presence
params[:strongbolt_user_group][:user_ids].present? &&
params[:strongbolt_user_group][:role_ids].present?
end
def validate_presence
if !check_presence
render json: { error: {
message: "Bad Request, parameters missing.",
status: 500 }
}
end
end
我必須包括型號名稱,檢查PARAMS存在,否則就沒有工作。現在我可以實現JS部分,在其中顯示某些消息不能空白的消息等,但這是不同的故事。現在我的控制器不會在Strongbolt寶石這個特殊情況下接受空的參數。
你有沒有考慮使用'save'代替'創建空白將返回true!'。 –
@SebastiánPalma我可以使用'save',但是我怎麼做驗證呢? – matiss
在控制器中執行它會非常難看,但至少您可以詳細說明一個邏輯來驗證此類參數何時「無」。 –