【问题标题】:ActiveRecord custom validadion error not preserved when building relations建立关系时未保留 ActiveRecord 自定义验证错误
【发布时间】:2014-11-13 16:10:09
【问题描述】:

我有模型:

class Agency < ActiveRecord::Base
  SPECIALIZATIONS_LIMIT = 5

  has_many :specializations
  has_many :cruise_lines, through: :specializations

  validate :validate_specializations_limit

  protected
    def validate_specializations_limit
      errors.add(:base, "Agency specializations limit is #{SPECIALIZATIONS_LIMIT}.") if specializations.count > SPECIALIZATIONS_LIMIT
    end
end

class CruiseLine < ActiveRecord::Base
  has_many :specializations
  has_many :agencies, through: :specializations
end

class Specialization < ActiveRecord::Base
  belongs_to :agency, inverse_of: :specializations
  belongs_to :cruise_line, inverse_of: :specializations
end

在我的服务中,我尝试像这样保存代理和专业化关系:

attributes = params.require(:agency).permit(
  :name, :website, :description, :booking_email, :booking_phone, 
  :optional_booking_phone, :working_hours, :cruise_line_ids => []
)

agency.update_attributes(attributes)

attributes[:cruise_line_ids].select{|x| x.to_i > 0}.each do |cruise_line_id|
  agency.specializations.build(cruise_line_id: cruise_line_id)
end

这段代码的工作原理:

1) 更新属性;

2) 如果我取消选中一些带有巡航线路的复选框,它会保存关系并更新它们;

3)如果我输入错误的数据或选择过多的游轮复选框,它不会保存数据,但也不会显示错误!

如果我在构建关系的块之后立即添加一些检查代码puts agency.errors.inspect - 它完全按照我的预期工作:如果所有内容都保存 - 显示成功消息,如果发生验证错误 - 显示错误消息。

问题:

为什么在保存代码后立即添加puts agency.errors.inspect 会使一切按预期工作?

【问题讨论】:

    标签: ruby-on-rails validation activerecord model


    【解决方案1】:

    我发现了错误:它在我的控制器中,总是在存储方法起作用后重定向到编辑页面(即使模型没有保存!)。控制器代码如下所示:

    if AgencyService.update_agency(current_agent.agency, params)
      flash[:success] = "Agency data updated successfully"
      redirect_to action: :edit
    else
      render :edit
    end
    

    我唯一要做的就是将此代码添加到我的 update_agency 方法的末尾

      # ... build relations
      return false if agency.errors.present?
      true
    end
    

    所以如果我的AgencyService.update_agency 返回 false - 用户没有被重定向并且所有错误都显示在页面上:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-16
      • 2022-06-11
      • 1970-01-01
      相关资源
      最近更新 更多