简体   繁体   中英

Rails: Populate inputs from a select tag in form

I'm running Rails 4 and 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) .

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:

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:

$(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. The JSON could look like:

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

See Rails Controller Overview: Rendering 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. Or is it merely to inform the user of previously made choices? In that case I'd recommend options_for_select . There are a lot of built-in helpers for selects:

ActionView Form Options Helpers

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. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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