选择user_id
后,collection_select :challenge_id
只能显示user_id
的挑战,而不是列出所有挑战?
<%= f.collection_select :user_id, User.order(:name),:id, :full_name, include_blank: true %>w
will
<%= f.collection_select :challenge_id, Challenge.order(:deadline),:id, :full_challenge, include_blank: true %>.
<%= f.collection_select :user_id, User.order(:name),:id, :full_name, include_blank: true, id: "id_of_the_user_id_select_box" %>w
will
<%= f.collection_select :challenge_id, Challenge.order(:deadline),:id, :full_challenge, include_blank: true %>.
<script>
$( "#id_of_the_user_id_select_box" ).change(function() {
$.ajax({
type: "GET",
url: '<%= user_challenges_path %>',
data: {name: $('#id_of_the_user_id_select_box').prop('value')}
});
});
</script>
challenges_controller
def user_challenges
# Not sure what to add in here
end
答案 0 :(得分:0)
在选择user_id
时触发ajax请求。像:
$( "#id_of_the_user_id_select_box" ).change(function() {
$.ajax({
type: "GET",
url: '<%= fetch_chanllenges_of_user_path %>', # replace by your route
data: {name: $('#id_of_the_user_id_select_box').prop('value')}
});
});
在routes.rb
文件上使用GET类型创建新路由。在该方法中,您获得了user_id
。现在找到该用户的各自挑战。然后使用部分替换第二个下拉列表。
修改强>
创建名为_user_challenges.html.erb
的新部分文件,并将以下代码粘贴到该文件
<div id="dropdown-no-2">
<%= collection_select 'challenge_id', challenges,:id, :full_challenge, include_blank: true %>.
</div>
在您的视图文件中,而不是使用第二个下拉列表,请使用此新创建的部分,如:
<%= f.collection_select :user_id, User.order(:name),:id, :full_name, include_blank: true, id: "id_of_the_user_id_select_box" %>w
will
# below code will be replaced
<%= f.collection_select :challenge_id, Challenge.order(:deadline),:id, :full_challenge, include_blank: true %>.
# by
<%= render :partial => 'user_challenges', locals: {challenges: Challenge.order(:deadline)} %>
# If you are using an intelligent IDE then the file path of user_challenges.html.erb file will be given as suggestion
在控制器中:
def user_challenges
# fetch challenges for a specific user
# I assumed that you've a one to many association between user and challenge
@user = User.find(params[:name])
@challenges = @user.challenges.order(:deadline)
end
现在,对于控制器的user_challenges
方法,创建一个名为user_challenges.js.erb
的视图文件。在该文件上写下以下内容:
$("#dropdown-no-2").html('<%=j render :partial => "user_challenges", locals: {challenges: @challenges} %>');
您也可以查看this。