How to solve this error:
[![enter image description here][1]][1]
I am trying to set custom validations method in model but i am getting
Routing Error undefined method `<' for nil:NilClass
This is article model code
# 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
This is code for 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
Remove these two lines from your article controller.Its outside your actions
a = Article.new
a.publish_date_cannot_be_more_than_one_month_from_today
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.