【问题标题】:Rails - validates_associated with an :if conditionRails - validates_associated 与 :if 条件
【发布时间】: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


【解决方案1】:

我知道出了什么问题。我的新出发构建器功能是为所有项目创建出发对象,无论它们是否是游轮。我添加了一个if Cruises?声明下面的代码,现在它可以正常工作了。

has_many :departures, :dependent => :destroy

def new_departure_attributes=(departure_attributes)
 departure_attributes.each do |attributes|
   if cruises? #new if statement
     departures.build(attributes)
   end
 end
end
#the following two methods are only used for update actions 
#(the error happens in new/create as well)
def existing_departure_attributes=(departure_attributes)
  departures.reject(&:new_record?).each do |departure|
    attributes = departure_attributes[departure.id.to_s]
    if attributes
      departure.attributes = attributes
    else
      departures.delete(departure)
    end
  end
end

def save_departures
  departures.each do |departure|
    departure.save(false)
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    相关资源
    最近更新 更多