简体   繁体   中英

How to make nested form for model with has_many :through association in Rails 5

So I have two models. One is Meal and the second is called Food. A meal can have multiple food items and a food item can be in multiple meals. Basically a many-to-many association. I did that with a has_many through association. The association model is called MealFood. I want to make a form so that when I'm creating a meal I have the option to select as many food items as I want either through a checkbox or a select option field. How can I achieve that? I'm very new to Rails so I don't even know where to begin. Any help would be amazing! Thanks in advance!

Here's my code so far:

class Meal < ApplicationRecord
    belongs_to :user
    has_many :meal_foods
    has_many :foods, through: :meal_foods
end

class Food < ApplicationRecord
    has_many :meal_foods
    has_many :meals, through: :meal_foods
end

class MealFood < ApplicationRecord
    belongs_to :meal
    belongs_to :food
end

Meals Controller

def index
end

def new
    @meal = Meal.new
    @meal.foods.new
end

def create
    @meal = Meal.new(meal_params)

    if @meal.save
        redirect_to @meal
    else
        render 'new'
    end
end

private

def meal_params
    params.require(:meal).permit(:meal_type, :date, :total_calories, :total_carbohydrates, :total_fat, foods_attributes: [:name, :calories, :proteins, :carbohydrates, :fat])
end

You don't need nested attributes to assign associations. All you really need is checkboxes or a select:

<%= form_with model: @meal do |f| %>
  # ...
  <%= f.collection_select(:foods_ids, Food.all, :id, :name) %>
  <%= f.submit %>
<% end %>

You then need to whitelist the attribute foods_ids attribute:

def food_params
  params.require(:food).permit(:foo, :bar, foods_ids: [])
end

This works as every many to many association has a _ids setter that takes an array of ids and replaces (or creates) the associations as needed.

Nested attributes is only needed if you need pass attributes for the associated records.

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