控制器#creal中的Rails 4 ArgumentError

时间:2014-04-15 19:58:16

标签: ruby-on-rails ruby

我正在尝试创建一个允许用户从youtube添加视频的Web应用程序 但得到ArgumentError in VideosController#create

  

提供的正则表达式使用多行锚点(^或$),这可能会带来安全风险。您的意思是使用\ A和\ z,还是忘记添加:multiline =>真的选择?

videocontroller.rb

class VideosController < ApplicationController


    def index
    @videos = Video.order('Created_at DESC')
  end


  def new
    @video = Video.new
  end

  def create
    @video = Video.new(video_params)
    if @video.save
        flash[:success] = 'Video Added!'
        redirect_to root_url
    else
        render 'new'
    end
  end

  def video_params
    params.require(:video).permit(:link)
  end
end

videos.rb

class Video < ActiveRecord::Base
  YT_LINK_FORMAT = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/i
  before_create -> do
    uid = link.match(YT_LINK_FORMAT)

    self.uid = uid[2] if uid && uid[2]

    if self.uid.to_s.length != 11
      self.errors.add(:link, 'is invalid.')
      false
    elsif Video.where(uid: self.uid).any?
      self.errors.add(:link, 'is not unique.')
      false
    else
      get_additional_info
    end
  end

    validates :link, presence: true, format: YT_LINK_FORMAT

  private

我是否将\A\z添加到YT_LINK_FORMAT行?

1 个答案:

答案 0 :(得分:1)

videos.rb中更改YT_LINK_FORMAT的定义:

YT_LINK_FORMAT = /\A.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*\z/i

(基本上用^替换您的初始\A,并将\z放在最后)

\A and \z匹配字符串的开头和结尾; ^ and $匹配行的开头和结尾。由于您没有将正则表达式定义为多行,因此您需要使用字符串匹配器而不是行匹配器。

这是错误试图告诉你的;这里有更好的描述:http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_format_of