我尝试在access_module_id
中验证关联的属性role
模型,但它不起作用。如何以presence: true
形式验证role
到其他模型的属性?这是协会
role.rb
class Role < ActiveRecord::Base
....
has_many :access_module_roles, :dependent => :destroy
has_many :access_modules, through: :access_module_roles
validates :name,:access_module_id, presence: true # I want to validate presence of access_module_ids in role form
end
access_module.rb
class AccessModule < ActiveRecord::Base
has_many :access_module_roles
has_many :roles, through: :access_module_roles
end
access_module_roles.rb
class AccessModuleRole < ActiveRecord::Base
belongs_to :access_module
belongs_to :role
end
我已尝试过以下验证,如果我选择一个,两个或所有仍然会收到错误,例如 &#34;访问模块ID不能为空白&#34;
validates_presence_of :access_module_ids
控制器
def create
@role = Role.new(role_params)
respond_to do |format|
if @role.save
params[:role][:access_module_ids].each do |acmi|
AccessModuleRole.create!(:role_id => @role.id, :access_module_id => acmi) if acmi!=""
end
format.html { redirect_to roles_path, notice: 'Role was successfully created.' }
format.json { render :index, status: :created, location: @role }
else
format.html { render :new }
format.json { render json: @role.errors, status: :unprocessable_entity }
end
end
end
答案 0 :(得分:0)
我发现我在Create
方法中犯了错误。我在保存后将数据插入AccessModuleRole
,因此在创建时会出现验证错误。并且参数为nil
更正后的代码:
def create
@role = Role.new(role_params)
@role.access_module_ids = params[:role][:access_module_ids]
respond_to do |format|
if @role.save
format.html { redirect_to roles_path, notice: 'Role was successfully created.' }
format.json { render :index, status: :created, location: @role }
else
format.html { render :new }
format.json { render json: @role.errors, status: :unprocessable_entity }
end
end
end
允许角色的属性:
private
def role_params
params.require(:role).permit(:name,:chk_ids ,:description, :code, :is_active, :access_module_ids)
end
现在它完美无缺..感谢RAJ指点我:)