简体   繁体   English

Rails-从表单选择下拉列表中向控制器传递参数

[英]Rails - pass a parameter to controller from form select dropdown

I have 2 models: Team and Quest . 我有2个模型: TeamQuest When creating a new team, I have a drop-down of all the quests. 创建新团队时,我会下拉所有任务。 When a quest is selected, I want to display information about the quest. 选择任务后,我要显示有关任务的信息。

My understanding is that everything in the form is on the client side and AJAX is required to pass the selected quest to the server side. 我的理解是,表单中的所有内容都在客户端,并且需要AJAX才能将选定的任务传递到服务器端。 My code is based on this Stack Overflow answer. 我的代码基于 Stack Overflow答案。

Here is how I constructed my form: 这是我构造表单的方式:

app/views/teams_form.html.erb app / views / teams_form.html.erb

<%= form_for(@team) do |f| %>
  <fieldset>
    <ol>
      <li>
        <%= f.label :name %>
        <%= f.text_field :name %>
      </li>
      <li>
        <%= f.label :quest_id %>
        <%= f.select :quest_id, 
                     options_from_collection_for_select(@quests, :id, :name), 
                     {}, {remote: true, url: '/teams/new', method: 'get'} %>
      </li>
      <% if @x != nil && @x.id != nil %>
        <li><%= @x.id %></li>
      <% end %>
    </ol>
    <p>
      <%= f.submit %>
    </p>
  </fieldset>
<% end %>

app/controllers/team_controller.rb app / controllers / team_controller.rb

def new
  @team = Team.new
  @quests = Quest.all
  respond_to do |format|
    if params[:quest_id] != nil
      @x = Quest.find(params[:quest_id])
    end
    format.html #new.html.erb
    format.json
    format.js
  end
end

My goal was to pass the :quest_id parameter from the form to the @x variable and use that in the form. 我的目标是通过:quest_id从表单参数的@x变量和使用形式。

This has produced nothing. 这什么也没产生。 I'm not getting the parameter in the controller and I'm not sure what I'm missing. 我没有在控制器中获取参数,也不确定要丢失什么。

As per the description shared it seems like the you are unable to get the value of the selected item from the dropdown. 按照共享的描述,您似乎无法从下拉列表中获取所选项目的值。

Below mentioned code is used for selecting value from dropdown also you can inspect the same using developer tools of the browser. 下面提到的代码用于从下拉列表中选择值,您也可以使用浏览器的开发人员工具进行检查。

quest = $("#quest_id").val();

Note: Assuming the selector id is quest_id, change it according to your form. 注意:假设选择器ID为quest_id,请根据您的表单进行更改。

Now, you can call the ajax using the below mentioned code. 现在,您可以使用下面提到的代码来调用ajax。

$.ajax({
  type: "GET",
  url: "/teams/new",
  data:{ quest_id: quest },
  dataType: "json",
  success:function(data){
    # logic for using ajax result
  }

Hope it helps!! 希望能帮助到你!!

Finally got this working, wanted to post if anyone sees this and is having the same problem: 终于解决了这个问题,如果有人看到并遇到相同的问题,我想发表一下:

I went with a separate AJAX request since that was being suggested 我提出了一个单独的AJAX请求,因为有人建议

app/views/teams_form.html.erb app / views / teams_form.html.erb

<script>
   $(document).ready(function() {
    $('#team_quest_id').change(function() {
       $.ajax({
         url: "/teams/new",
         data: {quest_id: $("#team_quest_id option:selected").val()},
         dataType: "script",
         method: "get",
         success: function(r){}
       });
     });
   });
</script>

I moved the location of the parameter assignment 我移动了参数分配的位置

app/controllers/team_controller.rb app / controllers / team_controller.rb

def new
  @team = Team.new
  @quests = Quest.all
  if params[:quest_id] != nil
    @x = Quest.find(params[:quest_id])
  end
  respond_to do |format|
    format.html #new.html.erb
    format.json
    format.js
  end
end

And most importantly - I created a js file to render my form 最重要的是-我创建了一个js文件来呈现表单

app/views/new.js.erb app / views / new.js.erb

$('#new_team').html("<%= j (render 'form') %>");

This video was extremely helpful 这部影片非常有帮助

The code in your question is almost correct, you forgot to nest the attributes in data . 您问题中的代码几乎是正确的,您忘记了将属性嵌套在data中

<% # app/views/teams_form.html.erb %>

<%= f.select :quest_id, 
                     options_from_collection_for_select(@quests, :id, :name), 
                     {}, {remote: true, url: '/teams/new', method: 'get'} %>
<% # should be: %>
<%= f.select :quest_id, 
                     options_from_collection_for_select(@quests, :id, :name), 
                     {}, {data: {remote: true, url: '/teams/new', method: 'get'}} %>
<% # or even better, use the path helper instead of the hard coded path %>
<%= f.select :quest_id, 
                     options_from_collection_for_select(@quests, :id, :name), 
                     {}, {data: {remote: true, url: new_team_path, method: :get}} %>

Having set the attributes correctly, we still need to fix the form further. 正确设置属性后,我们仍然需要进一步修复表单。 On page request the browser will request the form, but @x will never be set. 在页面请求中,浏览器将请求该表单,但是将永远不会设置@x Since ERB will not be send to the client we'll need to add a handle to find our quest container element back. 由于不会将ERB发送给客户端,因此我们需要添加一个句柄以找到我们的任务容器元素。

<% # app/views/teams_form.html.erb %>

<% if @x != nil && @x.id != nil %>
  <li><%= @x.id %></li>
<% end %>
<% # should be something like %>
<li id="quest-info-container"></li>

Now in the controller split of the HTML request from the JS request. 现在,在控制器中,将HTML请求与JS请求分开。

# app/controllers/teams_controller.rb

def new
  respond_to do |format|
    format.html do
      @team = Team.new
      @quests = Quest.all
    end
    format.js do
      @quest = Quest.find(params.dig(:team, :quest_id))
    end
  end
end

You could simplify the above by sending the select data-path to another url that handles the quest preview. 通过将选择数据路径发送到另一个用于处理任务预览的URL,可以简化上述操作。

Now we need to render the preview in our container we need 2 files for this, first of how the resulting structure should look. 现在我们需要在容器中渲染预览,为此我们需要2个文件,首先是结果结构的外观。 Keep in mind that this will be rendered inside the container. 请记住,这将在容器内部呈现。

<% # app/views/teams/_quest_preview.html.erb %>

<% # Here comes what you want to display about the quest. You can give this %>
<% # file another name if you like. You have @quest to your disposal here. %>
<%= @quest.id %> <strong><%= @quest.name %></strong>

Now we only need a JavaScript file that loads the above structure into our created handle. 现在,我们只需要一个JavaScript文件即可将上述结构加载到我们创建的句柄中。

<% # app/views/teams/new.js.erb %>

handle = document.getElementById('quest-info-container');
handle.innerHTML = '<%= j render('quest_preview') %>';

The j is an alias for escape_javascript . jescape_javascript的别名。 If the partial is not in the same directory use <%= j render('other_dir/some_partial') %> instead. 如果局部文件不在同一目录中,请使用<%= j render('other_dir/some_partial') %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将 Select2 下拉列表中的参数传递给 Kendo UI MVC 数据源 - Pass Parameter from Select2 Dropdown to Kendo UI MVC DataSource Rails将生成的js参数从表单传递给控制器 - Rails pass generated js params from form to controller 如何将参数从form_for方法传递到rails中的控制器方法? - how to pass argument from form_for method to controller method in rails? Ruby on Rails-在单击按钮时从Javascript下拉列表中选择的项目传递给Rails控制器 - Ruby on Rails - Pass item selected from a Javascript dropdown to Rails controller when a button is clicked 如何将选择/下拉值传递给表格2? - How to pass select/dropdown value to form 2? 获取URL参数并传递给Wordpress中的select - Get URL parameter and pass to form select in Wordpress 从控制器中的表单中选择不起作用 - Select from the Form in a Controller not working 如何将选择下拉列表的数据从Redux形式传递到Redux中的后端api - How to pass select dropdown's data from redux-form to backend api in redux 将Select2下拉框的选定值传递给控制器 - Pass the selected value of a Select2 dropdown box to controller 使用选择下拉列表使用ruby on rails参数更新link_to - Updating link_to with a ruby on rails parameter using a select dropdown
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM