首页 > 解决方案 > 在 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 一起使用。

标签: ruby-on-railsregexvalidationruby-on-rails-5

解决方案


推荐阅读