【发布时间】:2010-12-02 08:48:17
【问题描述】:
我在尝试将 :if 条件应用于 validates_related 验证时遇到了问题。 if 条件适用于 validates_presence_of,但不适用于 validates_associated,并且表单(其中包含两个模型)正常工作,除了验证仍然返回错误,无论 if 条件是真还是假。
validates_associated :departures, :if => :cruise?
validates_presence_of :ship_name, :if => :cruise?
def cruise?
item_marker == 1
end
# I even tested it using this, and it still returned a validated_associated error
def cruise?
false
end
#form item
<%= departure_form.date_select :date, :index => (departure.new_record? ? '' :
departure.id), :start_year =>Time.now.year, :order => [:month, :day, :year ],
:prompt=>true %>
我正在为 :departures 字段使用日期选择,并提示输入默认值(即每个字段的第一个选择选项具有 value="")。我相信这是导致问题的原因。我可以删除提示,并在控制器中删除 non_cruises 的出发日期,但这似乎很草率。有人有建议吗?请注意,此代码使用了 Ryan Bates 的“以一种形式处理多个模型”配方的部分内容。
【问题讨论】:
-
你能给我看看你的整个模型吗?你们有什么关系?
标签: ruby-on-rails validation forms conditional