【问题标题】:Rails 4 - Validate that at least one checkboxe is checked in nested form inside a loopRails 4 - 验证循环内至少有一个复选框以嵌套形式选中
【发布时间】:2018-05-23 22:18:22
【问题描述】:

我尝试使用一组复选框创建一个在嵌套 for 中工作的验证。

集合在 each.do 循环中。

<%= simple_form_for @questionnaire do |f| %>
    <% @questions.each do |question| %>
        <%= question.name %>
        <%= f.collection_check_boxes :answer_ids, Answer.where(question_id: question.id), :id, :content  %>
    <% end %>
<% end %>

这是在Questionnaire 表单中。

所以我尝试在Questionnaire 模型中验证answer,但我需要为每个问题都这样做:每个question 至少应该选中一个复选框。

任何想法都会很棒! 提前谢谢!

编辑:

我的3个模型之间的关系:

class Questionnaire < ActiveRecord::Base
  has_many :answers
  has_many :answers, :through => :answers
end

class Question < ActiveRecord::Base
    has_many :questionnaires
    has_many :answers, through: :questionnaires
end

class Answer < ActiveRecord::Base
  belongs_to :question
  has_many :questionnaires, :through => :answers
end

【问题讨论】:

  • 你如何确定这些answer_ids 属于这个question,我的意思是questionnariequestion 之间是否有任何关系,或者我错过了什么?
  • @rony36 好点,我更新了我的问题。

标签: ruby-on-rails ruby-on-rails-4 activerecord checkbox


【解决方案1】:

您需要验证answer_ids,如下所示

validates :answer_ids,  presence: true

这条线放在你的模型上

我想帮你

【讨论】:

  • 谢谢,但这不是需要做的:这只验证是否至少选中了一个复选框,所以如果对于问题 1 我选中一个复选框,它将发送表单,我需要验证对于每个问题,至少选中一个复选框。
猜你喜欢
  • 2014-07-15
  • 2017-07-27
  • 1970-01-01
  • 2011-03-13
  • 2015-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多