yolo
yolo

Reputation: 77

Rails presence validation with condition

Here is a piece of my member's model:

  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?"

I want to make it possible that a member which role is not player to subscribe whithout giving a team but the code i wrote doesn't seem to work.

Other thing, is it possible to make the team field appear if only the user selects player in role?

Here is _form of members:

  <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>

Upvotes: 0

Views: 102

Answers (2)

Austintacious1
Austintacious1

Reputation: 340

For your form, I would also recommend a bit of Javascript, like what I have below:

<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>

Like Robin said, this has nothing to do with RoR, and can be tackled with some quick scripting. When the page loads, you hide the field. When the user selects what type of member they are, if the value isn't what you want, you keep it hidden. Otherwise, reveal the hidden div.

Upvotes: 0

Robin
Robin

Reputation: 21884

validates :team, presence: { if: :player? }

def player?
    role == "player"
end

As for making the field appear, it's just a bit of javascript, it doesn't have anything to do with RoR. Hide the field by default, and add an event that triggers on change on the role select field. Depending on the value, show or hide the team field.

Upvotes: 1

Related Questions