Ruby on rails 仅当用户指定了某个值时才使字段有效,否则为可选

Ruby on rails 仅当用户指定了某个值时才使字段有效,否则为可选,ruby-on-rails,ruby,ruby-on-rails-5,wicked-gem,Ruby On Rails,Ruby,Ruby On Rails 5,Wicked Gem,有一个表单由用户提交,然后由模型验证。我只希望“省/州”字段验证“国家”是“CA”(加拿大)还是“US”(美国) 表单的设置稍有不同,因为我们正在从流程中执行多个步骤 这是控制器 def update case step when :step1 wizard_params = profile_params() wizard_params[:wizard] = 'step1' @profile =

有一个表单由用户提交,然后由模型验证。我只希望“省/州”字段验证“国家”是“CA”(加拿大)还是“US”(美国)

表单的设置稍有不同,因为我们正在从流程中执行多个步骤

这是控制器

    def update
        case step
        when :step1
          wizard_params = profile_params()
          wizard_params[:wizard] = 'step1'

          @profile = current_user.profile
          @profile.update(wizard_params)

          render_wizard @profile
end

    private
        def profile_params
          # There are more params although I stripped them for the simplicity of this example
          params.require(:profile).permit(:state_id, :country)
        end
Profile.rb

  belongs_to :state, :class_name => "ProvinceState", :foreign_key => :state_id, optional: true
我硬编码
可选:true
,但如果用户选择了CA/US或保存的字段是CA/US,我只希望可选:true

我看了一下lambda,它可能是我需要的东西

例如:

belongs_to :state, :class_name => "ProvinceState", :foreign_key => :state_id, optional: lambda | obj | self.country == CA || self.country == US ? true : false 
遗憾的是,您(当前)无法向
可选提供lambda-请参阅:

如果需要,Rails只需添加如下状态验证:

model.validates_presence_of reflection.name, message: :required
validates :state, presence: true, if: -> { %w[US CA].include?(country) }
因此,作为一种解决方法,您可以分两部分来完成这项工作:首先将关联指定为
可选
;然后明确规定您的条件需要:

belongs_to :state, :class_name => "ProvinceState", :foreign_key => :state_id, optional: true
validates :state_id, presence: true, if: ->{ %w[CA US].include?(country) }

如果逻辑变得非常复杂,您可能希望将其移动到单独的方法/类中,而不是内联lambda。请参阅:

您可以使用lambda条件进行如下验证:

model.validates_presence_of reflection.name, message: :required
validates :state, presence: true, if: -> { %w[US CA].include?(country) }