我正在执行before_validation,如下所示:
event.rb
attr_accessor :start_date
attr_accessible :start_time #recorded in database as a datetime
before_validation :build_start_time
...
def build_start_time
begin
self.start_time = DateTime.parse(start_date)
rescue
errors.add(:start_date, "invalid date")
return false
end
end
并且控制器看起来像:
def create
@event = events.build(params[:event])
if @event.save
# some other method calls
redirect_to @event
else
redirect_to :root
end
end
start_date由<%= f.text_field:start_date%>设置在窗体视图中调用,当我检查params时,它正确地传递给模型控制器的'Create'方法,但是在build_start_time方法中它是nil,因此没有设置self.start_time。你能解释为什么它会是零,解决方案是什么?我也尝试将其称为self.start_date,但这没有什么区别。
由于
答案 0 :(得分:2)
您是否尝试过start_date
也可以访问?
答案 1 :(得分:1)
您可以使用attr_accessible
致电start_date
,以便build()
可以实际设置它,或者您可以将控制器更改为:
def create
@event = events.build(params[:event])
@event.start_date = params[:event][:start_date]
if @event.save
# some other method calls
redirect_to @event
else
redirect_to :root
end
end
答案 2 :(得分:0)
tente assim。
#app/models/adm/video.rb
class Adm::Video < ActiveRecord::Base
validates :titulo, :url_codigo, presence: true
before_validation(on: [ :create, :update ]) do
self.url_codigo = parse_youtube(url_codigo) #url_codigo = params[:adm_video][:url_codigo]
end
private
# pega só o codigo do link youtube para inserir no banco
def parse_youtube(url)
if !url.blank?
regex = /(?:.be\/|\/watch\?v=|\/(?=p\/))([\w\/\-]+)/
return url.match(regex)[1] # https://www.youtube.com/watch?v=iX_rKHnKJSg = iX_rKHnKJSg
end
end
end
grava no banco dedadossócódigodovideo = iX_rKHnKJSg = https://www.youtube.com/watch?v=iX_rKHnKJSg = iX_rKHnKJSg。
数据库中的记录sò代码iX_rKHnKJSg video =#= https://www.youtube.com/watch?v=iX_rKHnKJSg iX_rKHnKJSg