假设我有一个模型与同一个类有两个has_one关联,因为我知道我需要两个。我想编写一个自定义验证方法来检查这些关联。假设球衣类有两个字符串,primaryColor
和secondaryColor
。
class SportsTeam < ActiveRecord::Base
has_one :homeJersey, class_name: 'Jersey', foreign_key: 'home_color'
has_one :awayJersey, class_name: 'Jersey', foreign_key: 'away_color'
validates :check_colors_do_not_reused
def check_colors_are_not_reused
# if :homeJersey.primaryColor == :awayJersey.secondaryColor
# errors.add(:awayJersey.secondaryColor, "change color of one of the jerseys")
# end
end
端
我对如何访问关联字段感到困惑,因为:homeJersey是一个符号。我是否必须在帮助程序中查询它?
由于
答案 0 :(得分:1)
它应该只是以下内容,因为Rails生成由符号命名的方法:
def check_colors_are_not_reused
if homeJersey.primaryColor == awayJersey.secondaryColor
errors.add(:awayJersey.secondaryColor, "change color of one of the jerseys")
end
end
除此之外:Ruby和Rails中的命名约定是用下划线命名,而不是使用camelcase。我建议您重命名关联和方法,以便进行如下调用:home_jersey.primary_color
。