簡體   English   中英

Rails驗證-確認存在未保存在模型中的表單屬性

[英]Rails validation - confirming presence of form attribute that is not saved in model

我的應用程序具有一個元素:foo的form_for標記,該標記未保存在模型中,用於form_for中使用的對象。

我需要使用Rails驗證助手來確認用戶是否為此元素提交了值。 但是,“狀態”驗證器將調用object.foo以確認其具有值。 由於foo沒有保存為對象的一部分,我該如何進行驗證?

謝謝!

您可能應該在控制器操作的params中檢查它的存在:

def create
  @model = MyModel.find(params[:id])
  unless params[:foo].present?
    @model.errors.add(:foo, "You need more foo")
  end

  # ...
end

如果:foo是對象的屬性,但未保存在數據庫中,並且您確實要使用ActiveRecord驗證,則可以為其創建attr_accessor ,並驗證存在性。

class MyModel < ActiveRecord::Base
  attr_accessor :foo
  validates :foo, presence: true
end

但這可能會導致保存無效記錄,因此您可能不想這樣做。

嘗試這個..

class SearchController < ApplicationController
  include ActiveModel::ForbiddenAttributesProtection

  def create
    # Doesn't have to be an ActiveRecord model
    @results = Search.create(search_params)
    respond_with @results
  end

  private

  def search_params
    # This will ensure that you have :start_time and :end_time, but will allow :foo and :bar
    params.require(:val1, :foo).permit(:foo, :bar , whatever else)
  end
end

class Search < ActiveRecord::Base
  validates :presence_of_foo

  private

  def presence_of_foo
    errors.add(:foo, "should be foo") if (foo.empty?) 
  end
end

在這里查看更多

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM