简体   繁体   English

Rails:以表格形式填充来自select标签的输入

[英]Rails: Populate inputs from a select tag in form

I'm running Rails 4 and Ruby 2. 我正在运行Rails 4和Ruby 2。

I am creating an app where you can track your calories and macronutrients through each meal you eat. 我正在创建一个应用程序,您可以在每餐中跟踪卡路里和大量营养素。

I'm adding a meal favourites page where the user can add meals they consistently eat. 我要添加一个“用餐偏爱”页面,用户可以在其中添加他们一直吃的饭。 I have done this through a favourites:boolean migration. 我已经通过一个收藏夹做到了:布尔迁移。

When a user creates a new meal I want to show them a drop down box of favourites they have already saved, by something like current_user.meals.where(favourite: true) . 当用户创建一顿新饭时,我想向他们显示一个他们已经保存的收藏夹的下拉框,例如current_user.meals.where(favourite: true)

When they click on one of their favourites from the drop down I would then like that information to populate the protein, carbs and fat inputs in the form. 当他们从下拉列表中单击自己的收藏夹之一时,我希望这些信息以表格的形式填充蛋白质,碳水化合物和脂肪。

What is the best way to do this? 做这个的最好方式是什么?

MealsController: MealsController:

class MealsController < ApplicationController

  .
  .
  .

  def new
    @meal = current_user.meals.build
  end

  def create
    @meal = current_user.meals.build(meal_params)

    respond_to do |format|
      if @meal.save
        format.html { redirect_to root_path, notice: 'Meal was successfully added.' }
      else
        format.html { render action: 'new', notice: 'Meal was not added.' }
      end
      format.js
    end
  end
  .
  .
  .

  private
    def set_meal
      @meal = Meal.find(params[:id])
    end

   .
   .
   .

end

New/Edit Meal Form 新/编辑餐单

<%= form_for(@meal) do |f| %>

  .
  .
  .

  <div class="field inline">
    <%= f.label :protein %> (g)<br>
    <%= f.text_field :protein %>
  </div>

  <div class="field inline middle">
    Carbs (g)<br>
    <%= f.text_field :carbohydrates %>
  </div>

  <div class="field inline right">
    <%= f.label :fats %> (g)<br>
    <%= f.text_field :fats %>
  </div>

  <div class="field actions">
    <%= f.check_box :favourite, class: "favourites" %> Add to Favourites?
  </div>

  <div class="actions">
    <%= f.submit "Save", class: "btn btn-large" %>
    <% if current_page?(edit_meal_path(@meal)) %>
      <%= link_to "Delete", @meal, class: "btn btn-large", method: :delete, data: { confirm: "Are you sure?" } %>
    <% end %>
  </div>

<% end %>

Thanks! 谢谢!

You can do it with JavaScript/jQuery: 您可以使用JavaScript / jQuery:

$(document).ready(function() {
  bindFavoriteMeal();
});

function bindFavoriteMeal() {
  $('#favorite_meal_select').change(function() {
    var mealId = $(this).val();
    var url = "/meals/" + mealId
    $.getJSON(url, function(data) {
      $.each(data, function(key, value) {
        var field = $("#" + key);
        if (field.length) {
          field.val(value);
        }
      });
    });
  });
}

The show action in your meals controller will have to respond to JSON, and you need to ensure that the form ids match with the JSON keys returned. 进餐控制器中的show操作将必须响应JSON,并且您需要确保表单ID与返回的JSON键匹配。 The JSON could look like: JSON可能类似于:

{ 'name': 'Mustart Salmon', 'protein': 40, 'carbs': 8, 'other_stuff': 'some_value' }

See Rails Controller Overview: Rendering JSON . 请参阅Rails Controller概述:呈现JSON

The implementation of the select dropdown will depend on what it's for. 选择下拉列表的实现将取决于其用途。 Is it for associating an item from the dropdown with the object being created? 是否用于将下拉菜单中的项目与正在创建的对象相关联? In that case check out the other answer by @jordan-davis. 在这种情况下,请查看@ jordan-davis的其他答案。 Or is it merely to inform the user of previously made choices? 还是仅仅是告知用户先前做出的选择? In that case I'd recommend options_for_select . 在这种情况下,我建议options_for_select There are a lot of built-in helpers for selects: 有很多内置的帮助器供选择:

ActionView Form Options Helpers ActionView表单选项助手

You would populate the dropdown with collection select 您将使用集合选择填充下拉列表

<%= collection_select :user, :meal, Meal.all, :id, :name, checked: meal.name.first %>

This code won't cut and paste, but it's to show the idea. 这段代码不会被剪切和粘贴,但这只是为了展示想法。 After that, you would have to use jQuery to grab the meal id, and then use that to populate the rest of the info. 之后,您将必须使用jQuery来获取餐ID,然后使用该ID填充其余信息。 You would start with something along the lines of: 您将从以下方面开始:

$(".dropdown-menu li a").click(function(){
    $(this).parents(".dropdown-menu:first").dropdown('toggle')
    var selectedMeal = $(this).text();

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM