【问题标题】:How to validate_presence_of with condition in a nested attributes?如何在嵌套属性中使用条件验证_presence_of?
【发布时间】:2015-09-29 02:36:41
【问题描述】:

我有模型 Question、Answer 和 AnswerDetail。

答案:

class Answer < ActiveRecord::Base
  has_many :answer_details, :dependent => :destroy
  accepts_nested_attributes_for :answer_details, :allow_destroy => true
  validates_associated :answer_details
end

答案详情:

class AnswerDetail < ActiveRecord::Base
  belongs_to :answer
  belongs_to :question
  validates_presence_of :answer_field, :if => lambda {isrequired == true}, :message => "This is required field"
end

isrequired 字段来自模型问题。

问题:

class Question < ActiveRecord::Base
  has_one :answer_detail
end

AnswerDetal 模型上有 question_idanswer_id 字段。如果 Question 模型中的 isrequire 字段等于 true,我想过滤 answer_field?我将如何做到这一点?如何访问模型内​​部的has_one关联属性?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 model nested-attributes


    【解决方案1】:

    我以前做过,虽然我现在手头没有代码:


    嵌套

    据我所知,您实际上可以将验证放在嵌套模型中:

    #app/models/question.rb
    class Question < ActiveRecord::Base
        validates :answer_field, presence: true, if: lambda {isrequired == true}
    end
    

    我强烈推荐使用新的validates 语法

    --

    inverse_of

    我确定我必须在我拥有的代码中某处使用inverse_of(抱歉,它已锁定在私人 GitHub 存储库中)。

    inverse_of 基本上包含了当前模型中的关联模型。就像您发现self.question.isrequired 的有效性一样:

    #app/models/answer_detail.rb
    class AnswerDetail < ActiveRecord::Base
      belongs_to :question, inverse_of: :answer_detail
      validates :answer_field, presence: true, if: lambda { question.isrequired == true }
    end
    
    #app/models/question.rb
    class Question < ActiveRecord::Base
      has_one :answer_detail, inverse_of: :question
    end
    

    但是,good news for you

    【讨论】:

    • 我对你的回答有点困惑?我需要将validates :answer_field, presence: true, if: lambda {isrequired == true} 放在问题模型上吗?为什么?
    【解决方案2】:

    这不是答案,这就是我的故障排除方法

    检查:

      validates_presence_of :answer_field, :if => lambda {isrequired == true}, :message => "This is required field"
    

    你有什么可用的变量,你可以用pry-rails gem 来做。像这样:

      validates_presence_of :answer_field, :if => lambda {binding.pry; isrequired == true}, :message => "This is required field"
    

    尝试保存问题时,您将获得一个交互式控制台(在服务器终端窗口中),您可以在其中打印 self 之类的值或执行以下操作:

      validates_presence_of :answer_field, :if => lambda {|record| binding.pry; isrequired == true}, :message => "This is required field"
    

    然后打印record

    然后您可以尝试查找Question 的存储位置:self.questionrecord.question

    【讨论】:

      【解决方案3】:

      我尝试使用self.question.isrequired,它正在工作。但也许您有其他很好的建议来进行错误验证。谢谢。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        相关资源
        最近更新 更多