首页 > 解决方案 > Add Record to Existing Collection in a Rails App

问题描述

I am attempting to develop a model in which a user can add the recipe they are viewing to an existing menu of recipes they have created, similar to adding a song to a custom playlist. I believe I have the models set up correctly (using a many to many through relationship) however I am unsure how to go about the adding of the actual records to a selected collection. Any guidance would be helpful. My code is as below.

Menus Controller

class MenusController < ApplicationController
before_action :set_search

def show
    @menu = Menu.find(params[:id])
end

def new
    @menu = Menu.new
end

def edit
    @menu = Menu.find(params[:id])
end

def create
    @menu = current_user.menus.new(menu_params)

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

def update
    @menu = Menu.find(params[:id])

    if @menu.update(menu_params)
        redirect_to @menu
    else
        render 'edit'
    end
end

def destroy
    @menu = Menu.find(params[:id])
    @menu.destroy

    redirect_to recipes_path
end

private
def menu_params
    params.require(:menu).permit(:title)
end
end

Menu Model

class Menu < ApplicationRecord
belongs_to :user
has_many :menu_recipes
has_many :recipes, through: :menu_recipes
end

menu_recipe Model

class MenuRecipe < ApplicationRecord
  belongs_to :menu
  belongs_to :recipe
end

Recipe Model

class Recipe < ApplicationRecord
belongs_to :user
has_one_attached :cover

has_many :menu_recipes
has_many :menus, through: :menu_recipes


end

User Model

class User < ApplicationRecord
has_secure_password
has_one_attached :profile_image
has_many :recipes
has_many :menus
end

标签: ruby-on-railsrubymodelcontrollerassociations

解决方案


You can do something like :

def add_recipe_to_menu
 menu = current_user.menus.find params[:id]
 recipe = current_user.recipes.find params[:recipe_id]

 menu.recipes << recipe
end

It will add a viewing recipe to existing menu of recipes.


推荐阅读