Для этого вы можете добавить скрипт java/coffee, так как это означает внесение изменений в форму в реальном времени.
Добавить текущего пользователя к данным и частичное (или два различных collection_selects с идентификаторами):
<%= f.select :user_id, User.order(:name).map { |user| [user.full_name, user.id] }, include_blank: true, id: "change-challenge-options", data: {current-user-id: current_user.id } %>
Добавить приложение/активы/JavaScripts/challengers.coffee
$(document).ready ->
userSelect = $('#change-challenge-options')
userSelect.on 'valuesChanged', ->
currentUserId = $('#current-challenge-options').data('current-user-id')
if(currentUserId == userSelect.val())
... show/hide the correct fields
else
... show/hide the correct fields
$(window).resize #Not necessary but makes it look nicer if the lists are long.
ли, если не знаете это лучшее решение, но я сделал что-то подобное в своем проекте, и он отлично работает.
EDIT: Итак, во-первых вам нужно добавить collection_select поля для обеих ситуаций на ваш взгляд, и поставлять их с идентификаторами:
<%= collection_select(:dueler, :challenge_id, @current_user_challenges, :id, :full_challenge, include_blank: true), id: "current-user-challenges" %>
<%= collection_select(:dueler, :challenge_id, @challenged_user_challenges, :id, :full_challenge, include_blank: true), id: "challenged-user-challenges" %>
Затем в сценарии нужно добавить:
if(currentUserId == userSelect.val())
$('#current-user-challenges').show()
$('#challenged-user-challenges').hide()
else
$('#challenged-user-challenges').show()
$('#current-user-challenges').hide()
Это отобразит/спрячет правильные поля. Я не совсем уверен в том, как добавлять идентификаторы в collection_selects, но если мое предложение не работает, просто поместите их в div или другой контейнер. Дайте эти контейнеры ids и покажите/скройте их таким же образом.
В дополнение к этому, возможно, вы захотите добавить какой-либо скрипт, охватывающий первые посещения или повторные посещения формы. Таким образом, полный код будет примерно таким:
#page:load just makes sure the page is fully loaded before running script.
#Usefull if you use turbolinks etc.
$(document).on 'ready page:load' ->
userSelect = $('#change-challenge-options')
currentUserId = $('#current-challenge-options').data('current-user-id')
$(window).on 'page:change', ->
if(userSelect.val()) #All none zero values are true in js
if(currentUserId == userSelect.val()) #Show the right field
$('#current-user-challenges').show()
$('#challenged-user-challenges').hide()
else
$('#challenged-user-challenges').show()
$('#current-user-challenges').hide()
else #Hide both fields if no user is chosen.
$('#challenged-user-challenges').hide()
$('#current-user-challenges').hide()
$(window).resize
userSelect.on 'valuesChanged', ->
if(currentUserId == userSelect.val())
$('#current-user-challenges').show()
$('#challenged-user-challenges').hide()
else
$('#challenged-user-challenges').show()
$('#current-user-challenges').hide()
$(window).resize
Надеюсь, он сработает для вас!
Вот рабочий фрагмент концепции с использованием JavaScript вместо кофе и необработанный HTML:
var userSelect = $('#change-challenge-options');
var currentUserId = $('#current-user-id').data('user-id');
$('#challenged-user-challenges').hide();
$('#current-user-challenges').hide();
userSelect.on('change', function() {
if (userSelect.val() == "0"){
$('#current-user-challenges').hide();
$('#challenged-user-challenges').hide();
}
else if (userSelect.val() == currentUserId) {
$('#current-user-challenges').show();
$('#challenged-user-challenges').hide();
} else {
$('#challenged-user-challenges').show();
$('#current-user-challenges').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<form id="new_challenge" role="form" accept-charset="UTF-8">
<div class="form-group" id="current-user-id" data-user-id = "1">
<label class="control-label col-sm-2">User:</label>
<select class="form-control" name="users" id="change-challenge-options">
<option selected="selected" value="0">Choose user...</option>
<option value="1">Me</option>
<option value="2">Other user</option>
</select>
</div>
<label class="control-label col-sm-2">Challenges:</label>
<div class="form-group">
<select class="form-control" name="users" id="current-user-challenges">
<option selected="selected" value="0">Choose challenge...</option>
<option value="1">My challenge 1</option>
<option value="2">My challenge 2</option>
</select>
</div>
<div class="form-group">
<select class="form-control" name="users" id="challenged-user-challenges">
<option selected="selected" value="0">Choose challenge...</option>
<option value="1">Other user challenge 1</option>
<option value="2">Other user challenge 2</option>
<option value="3">Other user challenge 3</option>
</select>
</div>
</div>
</form>
Можете ли вы объяснить, что you'r текущий результат является и то, что вы ожидаете получить? – slowjack2k
@ slowjack2k Я хочу перечислить проблемы для соответствующего ': user_id'.Как создать условное выражение так, что если ': user_id' будет равно' current_user', тогда будет отображаться '@ current_user_challenges', и если': user_id' будет равно '@ user', тогда отобразится' @ challengeed_user_challenges'. –
'@ challengeed_user_challenges' всегда содержит проблемы, которые вы ищете. Когда 'current_user == @ user', то' @challenged_user_challenges == @ current_user_challenges'. С данным кодом я не вижу необходимости в 'if'. – slowjack2k