有一个用户提交的表单,然后由模型验证。我只希望“省/州”字段验证“国家”是“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
简介.rb
belongs_to :state, :class_name => "ProvinceState", :foreign_key => :state_id, optional: true
我硬编码optional: 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