验证attr_accessor,Rails 4

时间:2016-04-09 22:43:54

标签: ruby-on-rails ruby validation ruby-on-rails-4

无论出于何种原因,我无法正确验证我的attr_accessor属性。

  attr_accessor :line1, :city, :postal_code, :state, :personal_id_number, :ssn_last_4, :bank_account_number, :bank_routing_number

  validates :line1, presence: true, if: :line1
  validates :city, presence: true, if: :city
  validates :postal_code, presence: true, length: { maximum: 10 }, if: :postal_code
  validates :state, presence: true, length: { maximum: 2 }, if: :state
  validates :personal_id_number, presence: true, numericality: { only_integer: true }, if: :personal_id_number
  validates :ssn_last_4, presence: true, length: { is: 4 }, numericality: { only_integer: true }, if: :ssn_last_4
  validates :bank_account_number, numericality: { only_integer: true }, if: :bank_account_number
  validates :bank_routing_number, numericality: { only_integer: true }, if: :bank_routing_number

使用此代码,所有属性都会通过验证是否应该进行验证。例如,postal_code即使超过10个字符也会通过,而其他字符即使空白也会通过。

如果我删除了if语句,则没有一个语句通过。我得到了每一个错误。例如,正确填写表单将显示city不能为空等等...

if语句需要存在,因为这些属性在创建时将为空白,并且只显示在edit表单上。

如何获得使用attr_accessor的验证?

1 个答案:

答案 0 :(得分:0)

如果数据库表根本没有备份该类,则可以使用ActiveModel来获取ActiveRecord功能。您需要做的就是在您的班级中包含该模型。然后验证将按照您对ActiveRecord的预期运行,并且您不需要条件。

import re
import requests

url = 'http://bbs.skykiwi.com/forum.php?mod=forumdisplay&fid=55&typeid=470&sortid=231&filter=typeid&pageNum=1&page=1'

sourceCode = getsourse(url) # source code of the url page
allLinksinPage = getallLinksinPage(sourceCode) #a List of the urls in current page
for eachLink in allLinksinPage:
    url = 'http://bbs.skykiwi.com/' + eachLink.encode('utf-8')
    html = getsourse(url) #THIS IS WHERE I CAN'T GET THE RIGHT SOURCE CODE


#To get the source code of current url
def getsourse(url):
    header = {'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows  NT 10.0; WOW64; Trident/8.0; Touch)'}
    html = requests.get(url, headers=header)
    return html.text

#To get all the links in current page
def getallLinksinPage(sourceCode):
    bigClasses = re.findall('<th class="new">(.*?)</th>', sourceCode, re.S)
    allLinks = []
    for each in bigClasses:
        everylink = re.findall('</em><a href="(.*?)" onclick', each, re.S)[0]
        allLinks.append(everylink)
return allLinks