如何成功调用AJAX来更新collection_select?

时间:2016-10-05 09:44:30

标签: javascript jquery ruby-on-rails ruby ajax

我们的想法是,challenges中的collection_select应根据用户select的身份而改变。

我们如何修复<script>以便列出用户的挑战?

决斗/ _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

<%= render partial: 'user_challenges', locals: { challenges: Challenge.order(:created_at) } %>

<script>
    $(document).ready(function(){
     # $( "#change-challenge-options" ).change(function() { // Doesn't fire if I put this line back in
      console.log("Fired!"); # Is firing
      $.ajax({
        url: '<%= user_challenges_path %>',
        type: 'GET',
        data: {name: $('#change-challenge-options').prop('value')},
       success:function(result)
       {
        alert('Successfully called');
       },
       error:function(exception){alert('Exeption:'+exception);} # But error is raising
      })
     # })
    })
</script>

决斗/ _user_challenges.html.erb

<div id="dropdown-no-2">
  <%= collection_select(:dueler, :challenge_id, challenges, :id, :full_challenge, include_blank: true) %>
</div>

决斗/ user_challenges.js.erb

$("#dropdown-no-2").html('<%=j render :partial => "user_challenges", locals: {challenges: @challenges} %>'); 

duels_controller

def user_challenges # Not sure if I should put @user & @challenges here or under def new
  @user = User.find(params[:id])
  @challenges = @user.challenges.order(:created_at)
end

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

0 个答案:

没有答案