[英]Routing Error undefined method `<' for nil:NilClass in rails
如何解決此錯誤:
[![在此處輸入圖像描述][1]][1]
我正在嘗試在模型中設置自定義驗證方法,但我得到了
路由錯誤未定義的方法 `<' for nil:NilClass
這是商品型號代碼
# article.rb
class Article < ActiveRecord::Base
validates_presence_of :category_id, :title, :body, :is_publish, :publish_date, :feature_image_url
validates_numericality_of :category_id, greater_than: 0
validates_length_of :title, minimum: 5
validates_length_of :body, within: 5..200
validates_uniqueness_of :title
validate :publish_date_cannot_be_more_than_one_month_from_today
def publish_date_cannot_be_more_than_one_month_from_today
if publish_date > (Date.today + 1.month)
errors.add(:publish_date, "Can't be more than 1 month from today")
end
end
end
這是articles_controller.rb 的代碼articles_controller.rb
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to articles_path
else
render action: "new"
end
end
def show
@article = Article.find(params[:id])
@category = Category.find(@article.category_id)
end
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
if @article.update_attributes(article_params)
redirect_to articles_path
else
render action: "new"
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
a = Article.new
a.publish_date_cannot_be_more_than_one_month_from_today
private
def article_params
params[:article].permit(:title, :body, :is_publish, :publish_date, :category_id, :feature_image_url)
end
end
從您的文章控制器中刪除這兩行。它在您的操作之外
a = Article.new
a.publish_date_cannot_be_more_than_one_month_from_today
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.