English 中文(简体)
具有模型的习俗验证:没有储蓄
原标题:Custom Validations with a Model: failing on save

我没有在网上找到任何伟大的例子,因此,我对我所期望的容易回答的问题提出了容易的问题。 兹特:

我有一个员额模式。

p = Post.find(1)
p.title = "This is the Title of this Article"
p.url_title = "this-is-the-title-of-this-article--created-by-user-name"

在设立该员额时,我根据标题设立了:url_职衔。 这就是我是如何在数据库中回避的,而不是披露正在流产和非描述的身份证。

我将这一标题放在前标题中,因此,我只能使用效力验证——独一无二,因为它认为,在以前的“ave”之前进行验证,而且有:有权验证。

因此,我需要确保:标题是独一无二的。 我附上了“逐个编号-#{p.user.name}”,以便不同用户能够多使用同一标题。

因此,我需要做的是一项惯例验证,确认: :url_title在储蓄之前是数据库独一无二的,如果不是独一无二,则会产生错误,并向用户通报。

Thoughts on the best way to do this?

最佳回答

用于创造名称

before_validation_on_create :create_url_title

....

private

def create_url_title
  url_title = .....
end

之后添加对卢尔_标题的适当确认

validate_uniqueness_of :url_title, :message => "This title is taken, please choose a different title"
问题回答

您可从<条码>之前的<条码/条码>移至<条码>>,直至>_validation <>条码>为止(见here。 这一挫折将产生和更新行动,因此我认为,这足以满足你的需要。

增 编

validates_uniqueness_of :url_title

页: 1 员额模式





相关问题
rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

SSL slowness in EC2

We ve deployed our rails app to EC2. In our setup, we have two proxies on small instances behind round-robin DNS. These run nginx load balancers for a dynamically growing and shrinking farm of web ...

Auth-code with A-Za-z0-9 to use in an URL parameter

As part of a web application I need an auth-code to pass as a URL parameter. I am currently using (in Rails) : Digest::SHA1.hexdigest((object_id + rand(255)).to_s) Which provides long strings like : ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

activerecord has_many :through find with one sql call

I have a these 3 models: class User < ActiveRecord::Base has_many :permissions, :dependent => :destroy has_many :roles, :through => :permissions end class Permission < ActiveRecord::...

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

How to get SQL queries for each user where env is production

I’m developing an application dedicated to generate statistical reports, I would like that user after saving their stat report they save sql queries too. To do that I wrote the following module: ...

热门标签