@user =选择的内容

时间:2016-09-08 10:25:08

标签: javascript ruby-on-rails ruby

选择:user_id时,我们如何在collection_select中显示该用户的挑战?换句话说,我们如何使@user等于_dueler_fields中选择的:user_id

决斗/ _form.html.erb

<%= simple_form_for(@duel) do |f| %>
  <%= f.fields_for :duelers do |dueler| %>
    <%= render 'dueler_fields', :f => dueler %>
  <% end %>
  <%= link_to_add_association f, :duelers do %>
    + Dueler
  <% end %>
  The loser(s) will <%= f.text_field :consequence, placeholder: "Enter Consequence" %>
<% end %>

决斗/ _dueler_fields.html.erb

<%= f.select :user_id, User.order(:name).map { |user| [user.full_name, user.id] } %>  will
<%= collection_select(:dueler, :challenge_id, @challenges, :id, :full_challenge) %>

duels_controller

def new
  @duel = Duel.new
  @duel.duelers << Dueler.new(user_id: current_user.id, user_name: current_user.name, user_last_name: current_user.last_name)
  @user = # How can we set this to whatever was selected?
  @challenges = @user.challenges.order(:created_at)
end

schema.rb

  create_table "duelers", force: true do |t| #belongs_to :user & :challenge & :duel
    t.integer  "user_id"
    t.integer  "challenge_id"
    t.datetime "created_at",     null: false
    t.datetime "updated_at",     null: false
    t.integer  "duel_id",        null: false
    t.boolean  "accept"
    t.string   "user_name"
    t.string   "user_last_name"
    t.string   "challenge_name"
  end

  add_index "duelers", ["duel_id"], name: "index_duelers_on_duel_id", using: :btree

  create_table "duels", force: true do |t| #belongs_to :user & :challenge, has_many :duelers
    t.text     "consequence"
    t.text     "reward"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

更新

<%= 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, @challenges, :id, :full_challenge, include_blank: true) %>

<script> # Doesn't Work
    $( "#change-challenge-options" ).change(function() {
         $.ajax({
            type: "GET",
            url: '<%= user_challenges_path %>',
            data: {name: $('#change-challenge-options').prop('value')}
         });
    });
</script>

1 个答案:

答案 0 :(得分:0)

在刷新页面时没有必要去控制器来获取用户挑战,解决它的最佳形式似乎得到一个功能,将挑战返回到从&#34;更改&#34;激活的json请求中。 users_id的操作选择

在users_controller中:

def challenges
  user = User.find_by_id(user_params)
  @challenges = user.challenges.order(:created_at)
  respond_to |format|
    format.js { render json: @challenges.as_json, status: 200 }
  end
end

def user_params
  params.require(:user).permit(:user_id)
end

在javascript中:

$("#user_select").on("change", function(){
// make ajax petition with the user: {user_id: $(this).val()}
// and rescue the results to display wher you want
})