Note that there are some explanatory texts on larger screens.

plurals
  1. PORails: Populate inputs from a select tag in form
    primarykey
    data
    text
    <p>I'm running Rails 4 and Ruby 2. </p> <p>I am creating an app where you can track your calories and macronutrients through each meal you eat.</p> <p>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. </p> <p>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 <code>current_user.meals.where(favourite: true)</code>. </p> <p>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.</p> <p>What is the best way to do this?</p> <p><strong>MealsController:</strong> </p> <pre><code>class MealsController &lt; 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 </code></pre> <p><strong>New/Edit Meal Form</strong></p> <pre><code>&lt;%= form_for(@meal) do |f| %&gt; . . . &lt;div class="field inline"&gt; &lt;%= f.label :protein %&gt; (g)&lt;br&gt; &lt;%= f.text_field :protein %&gt; &lt;/div&gt; &lt;div class="field inline middle"&gt; Carbs (g)&lt;br&gt; &lt;%= f.text_field :carbohydrates %&gt; &lt;/div&gt; &lt;div class="field inline right"&gt; &lt;%= f.label :fats %&gt; (g)&lt;br&gt; &lt;%= f.text_field :fats %&gt; &lt;/div&gt; &lt;div class="field actions"&gt; &lt;%= f.check_box :favourite, class: "favourites" %&gt; Add to Favourites? &lt;/div&gt; &lt;div class="actions"&gt; &lt;%= f.submit "Save", class: "btn btn-large" %&gt; &lt;% if current_page?(edit_meal_path(@meal)) %&gt; &lt;%= link_to "Delete", @meal, class: "btn btn-large", method: :delete, data: { confirm: "Are you sure?" } %&gt; &lt;% end %&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload