ruby-on-rails - 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
解决方案
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.
推荐阅读
- html - CSS在按钮上方对齐绝对div
- delphi - 如何将参数传递给现有的应用程序实例
- tensorflow - 导入tensoflow_hub时如何克服“没有名为'keras'的模块”
- numpy - 请解决正文中提到的numpy问题
- java - 了解 Android Studio 中的 FileProvider
- pine-script - Pine 脚本冷却一定数量的酒吧
- r - DESeqDataSetFromHTSeqCount 无法识别我的目录
- python - TD游戏和敌人瞄准
- plantuml - Mix classes and use cases in PlantUML diagram
- installation - MSYS2 安装程序