2016-10-07 2 views
0

Как создать условное выражение, где, если dueler является current_user, тогда он перечислит вызовы current_user, и если dueler будет @user, тогда он перечислит проблемы @ пользователя?Условный для вложенного атрибута?

duels_controller

def new 
    @user = User.find(params[:challenge_daddy]) 
    @duel = Duel.new 
    @duel.duelers << Dueler.new(user_id: current_user.id, user_name: current_user.name, user_last_name: current_user.last_name) 
    @duel.duelers << Dueler.new(user_id: @user.id, user_name: @user.name, user_last_name: @user.last_name) 
    @current_user_challenges = current_user.challenges.order(:created_at) 
    @challenged_user_challenges = @user.challenges.order(:created_at) 
    respond_with(@duel) 
end 

дуэлей/_form.html.erb

<%= simple_form_for(@duel) do |f| %> 
    <%= f.fields_for :duelers do |dueler| %> 
    <%= render 'dueler_fields', :f => dueler %> 
    <% end %> 
    The loser will <%= f.text_field :consequence %>. 
    <%= f.submit %> 
<% end %> 

дуэлей/_dueler_fields.html.erb

<%= f.select :user_id, User.order(:name).map { |user| [user.full_name, user.id] }, include_blank: true, id: "change-challenge-options" %> will 
<%= collection_select(:dueler, :challenge_id, # @challenged_user_challenges or @current_user_challenges 
, :id, :full_challenge, include_blank: true) %> 

Как создать условный, так что если :user_id равно current_user тогда @current_user_challenges покажет в collection_select и если :user_id равно @user тогда @challenged_user_challenges покажет?

+0

Можете ли вы объяснить, что you'r текущий результат является и то, что вы ожидаете получить? – slowjack2k

+0

@ slowjack2k Я хочу перечислить проблемы для соответствующего ': user_id'.Как создать условное выражение так, что если ': user_id' будет равно' current_user', тогда будет отображаться '@ current_user_challenges', и если': user_id' будет равно '@ user', тогда отобразится' @ challengeed_user_challenges'. –

+0

'@ challengeed_user_challenges' всегда содержит проблемы, которые вы ищете. Когда 'current_user == @ user', то' @challenged_user_challenges == @ current_user_challenges'. С данным кодом я не вижу необходимости в 'if'. – slowjack2k

ответ

1

Для этого вы можете добавить скрипт 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>

+0

Извините, если вы не сообщите о специфике «показать/скрыть правильные поля»? Я плохо знаю javascript:/Было бы очень благодарно! :) –

+0

Отредактировал мой ответ еще с кодом! Удачи! – Ozgar

+0

Если это решило вашу проблему, пожалуйста, отметьте ее как разрешенную. – Ozgar

Смежные вопросы