簡體   English   中英

有條件的Rails驗證

[英]Rails presence validation with condition

這是我的會員模型的一部分:

  belongs_to :team
  validates :role, inclusion: { in: %w(administrator visitor player),
    message: "%{value} is not a valid size" }, allow_nil: true
  validates :email, presence: true, uniqueness: true, on: :create 
  validates :team,  presence: true, :if => "member.role=player?"

我想讓一個角色而不是玩家訂閱的成員在沒有給團隊的情況下就訂閱,但是我編寫的代碼似乎不起作用。

另外,如果只有用戶選擇角色的玩家,是否可以使團隊字段出現?

這是成員的_form:

  <div class="field">
    <%= f.label :email %><br>
    <%= f.text_field :email %>
  </div>
  <div class="field">
    <%= f.select :role, ['visitor','administrator','player'] %>
  </div>
  <div class="field">
    <%= f.label :team_id %><br>
    <%= f.number_field :team_id %>
  </div>
validates :team, presence: { if: :player? }

def player?
    role == "player"
end

至於使該字段顯示,它只是一些javascript,它與RoR沒有任何關系。 默認情況下隱藏該字段,並添加一個事件,該事件在角色選擇字段上的change時觸發。 根據值,顯示或隱藏團隊字段。

對於您的表單,我還建議您使用一些Javascript,如下所示:

<script type="text/javascript">

$(document).ready(function() {
    // Hide the div when the page is loaded
    $('#team_field').hide();

    // Install a change handler to unhide the div if the user selects other than
    // what you want
    $('#player_type_select_box').change(function() {
        var val = this.value;
        if (val == 1 || val == 2) {
            // Hide the other input
            $('#team_field').hide();
        } else {
            // Unhide
            $('#team_field').show();
        }
    });
});

</script>

如Robin所說,這與RoR無關,可以通過一些快速腳本來解決。 頁面加載后,您將隱藏該字段。 當用戶選擇成員類型時,如果該值不是您想要的值,則將其隱藏。 否則,顯示隱藏的div。

暫無
暫無

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

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