Rails:奇怪的验证错误

时间:2011-08-10 11:32:48

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

我有一个Location模型,其字段为:

Location(id: integer, name: string, address: string, latitude: decimal, longitude: decimal, created_at: datetime, updated_at: datetime, rating: decimal, rating_count: integer)

在我的location模型中,我有以下验证(工作正常):

attr_accessible :name, :address, :latitude, :longitude, :rating, :rating_count

validates :name, :presence => true, :length => { :maximum => 50 }
validates :address, :presence => true
validates :rating, :inclusion => 0..5
validates :rating, :presence => { :message => " cannot be blank" }

我还有Post模型,其字段为:

Post(id: integer, user_id: integer, location_id: integer, info: string, created_at: datetime, updated_at: date time)

以下验证:

attr_accessible :info, :address, :name, :rating
belongs_to :user
belongs_to :location
attr_accessor :rating, :address, :name #Virtual attributes for the Post create form

validates :name, :presence => true, :length => { :maximum => 50 }
validates :address, :presence => true
validates :rating, :inclusion => 0..5
validates :rating, :presence => { :message => " cannot be blank" }

现在,问题当我尝试创建新的Post时,nameaddress的验证工作正常(就像它们的工作一样)对于Location),但rating的验证始终失败。即使我输入{3}的rating,我也会因某种原因收到错误Rating is not included in the list,但如果直接与{{1}一起使用,{3}的rating也会被正确验证行动。

有人知道为什么只有Location#create验证无法按预期与rating一起工作,即使它与Post一起正常工作,其他验证与两个模型的行为相同?

编辑:以下是来自Location的{​​{1}}操作:

create

我知道这是一个很大的帖子,但重点是,2个相同的验证在一个地方失败,在另一个地方取得成功。其中一个验证属于数据库的属性,另一个验证虚拟属性,我怀疑这是潜在的问题。

2 个答案:

答案 0 :(得分:1)

validates :rating, :inclusion => ['0', '1', '2', '3', '4', '5']
# OR
validates :rating, :inclusion => (0..5).map(&:to_s)

<强> UPD

添加此方法

def rating=param
  @rating = param.to_f
end

现在您可以使用原始验证

validates :rating, :inclusion => (0..5)

答案 1 :(得分:0)

您需要在评分中存储整数值3,而不是字符串"3"

类似的东西:

model.rating = params[:rating].to_i