简体   繁体   中英

Rails 4: Iterate through an array to create model in controller

I pass parameters from a view to a controller. The parameter is an array that is generated by the user. The user can add as many items to the array as they want. I want to iterate through this array to create multiple model objects in the DB. How can I go about doing this?

A person can create a meal, and within the meal form, there are options to add as many food items as they wish.

def create
    @meal= Meal.new(question_params)
    food_options = params[:food_options]
    i = 0
    if @meal.save
    food_options.each do |x| 
        @meal.foods.Create(:drink => food_option[i], :meal => @meal)
        i = +1
     end
   redirect_to @meal
else
  render 'new'
end

end

Any guidance would be much appreciated

Use accepts_nested_attributes_for and let Rails handle it for you.

In the models/meal.rb

class Meal < ActiveRecord::Base
  has_many :foods
  accepts_nested_attributes_for :foods   # <==========
  ...
end

and in the controller, include the nested attributes:

class MealsController < ApplicationController
  ...
  def create
    @meal= Meal.new(question_params)
    redirect_to @meals
  else
    render 'new'
  end
  ... 
  def question_params
    params.require(:meal).permit(...., foods_attributes: [ :drink, .... ])  # <====
  end
end

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