我的Tag
模型对属性name
有一些验证。在其他所有情况下都很好。但是当我通过这种方式拨打find_or_create_by_name
:`find_or_create_by`方法正在跳过模型验证。为什么?
# The last value of this string (by coma) is empty.
# So this record should not be saved.
tags_line = 'ruby, javascript, '
tags_line.split(',').each do |tag_name|
tag = Tag.find_or_create_by_name(tag_name.strip) do |new_tag|
new_tag.update_attribute :user_id, member.user.id
end
# Just append tag to this model
# through `has_and_belongs_to_many :tags`
tags << tag if tag
end
但是这个空标签甚至被保存。那么,在这段代码中可能会出错?
注:当我删除块,它的工作原理:
...
tags_line.split(',').each do |tag_name|
# This way, invalid tag will not be created.
tag = Tag.find_or_create_by_name(tag_name.strip)
tags << tag if tag
end
它可以为空值工作,但我想验证格式,长度等。所以我寻找这个问题的根源,避免重复的验证。 Tks – 2012-04-19 16:29:34
你说得对,对不起。误解了你的问题。我在那里添加了更多信息 – Christian 2012-04-19 16:40:28