小编one*_*one的帖子

如何使用 Shoulda 正确检查唯一性和范围

我有一个User具有items. 该:name项目的应该是用户唯一的,但它应该允许不同的用户拥有的项目具有相同名称。

Item 模型当前设置为:

class Item < ApplicationRecord
  belongs_to :user
  validates :name, case_sensitive: false, uniqueness: { scope: :user }
end
Run Code Online (Sandbox Code Playgroud)

这适用于验证内部用户,但仍允许其他用户使用相同的名称保存项目。

我如何使用 RSpec/Shoulda 进行测试?

我目前的测试是这样写的:

describe 'validations' do
    it { should validate_uniqueness_of(:name).case_insensitive.scoped_to(:user) }
  end
Run Code Online (Sandbox Code Playgroud)

但是这个测试失败了,因为:

Failure/Error: it { should validate_uniqueness_of(:name).scoped_to(:user).case_insensitive }

       Item did not properly validate that :name is case-insensitively
       unique within the scope of :user.
         After taking the given Item, setting its :name to ‹"an
         arbitrary value"›, and saving it as the existing …
Run Code Online (Sandbox Code Playgroud)

rspec shoulda

3
推荐指数
1
解决办法
2333
查看次数

如何将 before_action 与 :unless 和 params 一起使用

我有一个授权模块,用于授权用户操作。一切都运行良好,但现在如果请求页面的用户是当前用户,我想跳过该操作。该资源嵌套在下面user,因此将 a:user_id作为参数的一部分传递。

据我所知,最简单的方法是使用 lambda,但我似乎无法访问 before 过滤器传递的参数。

这是我的控制器

class Certifications::FitnessController < ApplicationController
  prepend_before_action :authenticate_user!
  before_action :authorize, unless: -> { params[:user_id] == current_user.id }
end
Run Code Online (Sandbox Code Playgroud)

问题是:authorizebefore_action 永远不会被调用,因此所有操作都是允许的(我假设是因为 except 语句总是评估为 true),但我无法检查发生了什么,因为如果我在那里停止执行,似乎没有参数在那里(我认为这应该使它总是评估为假,而不是真)。

如果有人能告诉我我做错了什么或更好的实施方法,我将非常感激。

编辑:如果将参数转换为整数以匹配 current_user.id,上面的代码实际上可以工作

before_action :authorize, unless: -> { params[:user_id].to_i == current_user.id }
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails

3
推荐指数
1
解决办法
4793
查看次数

简单的JavaScript函数返回函数而不是值

我刚刚开始,我正在尝试构建一个简单的计算函数,它将在页面上显示2个数字的结果.当按下提交按钮时,输出是函数而不是值.我哪里出错了?

HTML

<div id="input">
<form id="start">
  <input id="price" type="number" placeholder="What is the starting price?" value="10">
  <input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
</div>
<div id="test">Test</div>
Run Code Online (Sandbox Code Playgroud)

JS

<script>
'use strict';

var total = function() {

  var price = function() {
    parseFloat(document.getElementById("price"));
  }

  var tax = function() {
    parseFloat(document.getElementById("tax"));
  }
  var final = function() {
    final = price * tax;
    final = total
  }

  document.getElementById("output").innerHTML = final;

};
</script>
Run Code Online (Sandbox Code Playgroud)

javascript

1
推荐指数
1
解决办法
127
查看次数

标签 统计

javascript ×1

rspec ×1

ruby-on-rails ×1

shoulda ×1