Html Rails重定向到控制器/操作将丢失所有模型错误

Html Rails重定向到控制器/操作将丢失所有模型错误,html,ruby-on-rails,redirect,model,Html,Ruby On Rails,Redirect,Model,我的用例很简单,在一个名为dashboard/incomers的页面中,我显示一个表单来更新类型为incomesting的记录 #income-setting-form h4 Income Settings p Please set your Income Settings using the form below. = render 'income_settings/form' 这将生成用于编辑此类型obejct的表单: = simple_form_for @income_se

我的用例很简单,在一个名为
dashboard/incomers
的页面中,我显示一个表单来更新类型为
incomesting
的记录

#income-setting-form
  h4 Income Settings
  p Please set your Income Settings using the form below.

  = render 'income_settings/form'
这将生成用于编辑此类型obejct的表单:

= simple_form_for @income_setting do |f|

  = f.hidden_field :user_id

  = f.error_notification

  .form-group
    = f.label :amount
    = f.input_field :amount, required: true, class: 'form-control'
    = f.error :amount, id: 'amount_error'

  = f.association :income_frequency_type, label: 'Frequency:', collection: IncomeFrequencyType.order('id ASC'), include_blank: false, wrapper_html: { class: 'form-group' }, input_html: { class: 'form-control' }

  .form-group
    = f.label :start_date
    = f.input_field :start_date, required: true, as: :string, class: 'form-control datepicker'
    = f.error :start_date, id: 'start_date_error'

  = f.association :savings_rate_type, label: 'Savings Rate:', collection: SavingsRateType.order('name ASC'), include_blank: false, wrapper_html: { class: 'form-group' }, input_html: { class: 'form-control' }

  .form-group
    = f.label :description
    = f.input_field :description, required: true, class: 'form-control'
    = f.error :description, id: 'amount_error'

  button.btn.btn-primary.btn-block type='submit' Save
为了让事情保持安静和易于维护,我决定将
incomesting
对象的所有操作都保存在
income\u settings\u controller.rb
文件中

  def update
    if @income_setting.update(income_setting_params)
      redirect_to dashboard_income_path, notice: 'Your Income Setting was saved successfully updated.'
    else
      redirect_to controller: 'dashboard', action: 'income'
    end
  end
看到验证失败的地方了吗,我重定向到仪表板?如果我在那里放置一个断点,我可以看到模型
@income\u设置
确实存在验证错误-但是就像控制器重定向一样,模型错误丢失了


关于如何持久化这些错误以使它们在调用
渲染“收入”设置/表单时实际显示的任何建议?

您需要渲染
仪表板/income
,而不是在错误条件下重定向。由于将表单请求发送到单独的控制器,因此可能需要重复/共享用于呈现该页面的设置逻辑:

def update
  if @income_setting.update(income_setting_params)
    redirect_to dashboard_income_path, notice: 'Your Income Setting was saved successfully updated.'
  else
    # additional setup may be necessary
    render 'dashboard/income'
  end
end

是故意的。重定向丢弃状态。您需要渲染,而不是重定向。@米格尔:如果我进行渲染,我需要在一个完全不相关的控制器中实例化我在
仪表板#
中创建的所有其他实例变量。。。没有其他方法吗?没有,这是Rails中非常常见的模式;错误时渲染,成功时重定向。这就是几乎每一个“创建”和“编辑”操作应该如何工作。如果您想要一种可以说是“更好”的方式,请通过AJAX进行创建,并且永远不要离开
仪表板#索引
视图。如果我进行渲染,我需要在一个完全不相关的控制器中实例化我在
仪表板#
中创建的所有其他实例变量。。。没有其他方法吗?您可以呈现只需要要实例化的数据的视图,如果需要呈现仪表板/收入模板,则必须实例化模板所需的所有数据。如果你不想要重复的代码,你可以使用一个私有方法来实现这一点,只要在正常操作中调用这个私有方法,然后在模板呈现之前,如果控制器是“完全不相关的”,那么,为什么你会有一个关系呢?也许你得考虑重新设计一下。