ruby-on-rails - 在 Rails 中使用正则表达式进行格式验证获取:'未定义的局部变量或方法'
问题描述
我有一个 Product 模型,它具有我要验证的 :image_url 属性:
class Product < ApplicationRecord
validates :image_url, allow_blank: true, format:
{ with: /\w+\.(gif|jpg|png)\z/i,
message: "Image must have GIF, JPG, or PNG extension"
}
end
格式验证的目的是允许所有以 .gif、.png 或 .jpg 结尾的 url。正则表达式似乎工作正常,这是 Rubular 链接:
http
://rubular.com/r/GQx0oAaI1x
但是当尝试访问我的应用程序(任何视图或控制台)时,我得到:
undefined local variable or method `image_url' for #<Class:0x007f84c9baf0b8>
这是我的架构:
create_table "products", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "image_url"
t.decimal "price", precision: 8, scale: 2
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
我数据库中的所有产品都有适当的image_url
. 我不明白为什么该错误告诉我image_url
是未知方法 forClass
而不是 for Product object
。
这是我的服务器日志:
Started GET "/products" for 127.0.0.1 at 2018-09-05 14:09:55 +0200
Processing by ProductsController#index as HTML
Completed 500 Internal Server Error in 21ms (ActiveRecord: 3.8ms)
NameError - undefined local variable or method `image_url' for <Class:0x00007fc3651c1e40>:
app/models/product.rb:5:in `<class:Product>'
app/models/product.rb:1:in `<main>'
app/controllers/products_controller.rb:7:in `index'
这是我在 ProductsController 中的索引操作:
def index
@products = Product.all
end
这是我的index.html.haml
:
%h1 Your Pragmatic Catalog
%ul.catalog
- @products.each do |product|
%li
= image_tag(product.image_url)
%h2= product.title
%p
= sanitize(product.description)
.price
= number_to_currency(product.price)
谁能帮我理解问题出在哪里?
我将 ruby 2.5.1 与 Rails 5.2.1 一起使用。
解决方案
推荐阅读
- xpath - 将字符串乘以整数?
- git - 如何管理在每个 git 版本中添加私有代码片段?
- android - AlarmManager + NotificationManager 不工作
- javascript - 如何将值 onClick 从不同组件分配给 React 中的另一个组件
- python - Slice(...) 是无效键
- visual-studio - 如何在 Visual Studio 2019 中将文件名放入代码片段
- deep-learning - GPU 资源耗尽错误
- oop - OOP:如果在对象被销毁时组件被销毁但该组件可以在不同对象之间使用相同,那么它是组合吗?
- autodesk-forge - Forge - 检索 BIM360 传输信息
- c# - 从模型传递到 BLL 到 DAL