我正在努力寻找一种方法来验证命名范围的参数。
说明性设置:
models/products.rb
scope :country, -> country {where(:country_id => country)}
controllers/product_controller.rb
has_scope :country, :type => :array
表架构:
create_table "products", force: :cascade do |t|
t.string "name", limit: 255
t.integer "country_id", limit: 4
end
示例 A: localhost:3000/products?country_id=1
按预期返回有效产品
示例 B: localhost:3000/products?country_id=111111111111111111111
返回 111111111111111111111 超出 ActiveRecord::Type::Integer 的范围,限制为 4
这是有道理的,因为我已将 country_id 列限制为 4。但我不想增加列限制,而是想在运行命名范围“country”之前验证恶意的 country_id。
我研究过:
- guides.rubyonrails.org/active_record_validations.html(适用于 仅用于保存到数据库)
- guides.rubyonrails.org/routing.html(分段约束)
有什么想法吗? 谢谢
最佳答案
您可以强制范围只读取 country_id
值的前 4 位数字:
scope :country, -> country { where(:country_id => country.to_s[0..3].to_i) }
但是看起来很丑...
在我的 IRB 中:
1.9.3p392 :003 > 355555454.to_s[0..3].to_i
=> 3555
1.9.3p392 :004 > 3.to_s[0..3].to_i
=> 3
或者最终没有返回结果:
scope :country, -> country do
if country.to_s.length > 4
where(id: -1)
else
where(:country_id => country)
end
end
关于ruby-on-rails - 命名范围的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29218543/