我在rails应用程序上创建一个类似于zapier或ifttt的基本ruby。用户创建食谱。我只想显示用户创建的食谱。
我已经使用设备gem进行身份验证。
我的问题:
我是否添加"如果是user_signed_in?"在每页的顶部?我可以在应用程序布局上添加以上产量吗?有没有更好的办法?
我是否在用户中嵌套食谱?
答案 0 :(得分:0)
假设您在用户和食谱之间有很多关联
你可以这样做。使用设计提供的current_user帮助程序并使用current_user来引用您的配方。
因此,在任何有关食谱的页面上,您只需要查询用户创建的食谱。
class RecipesController < ApplicationController
before_action :set_recipe, only: [:show, :edit, :update, :destroy]
# GET /recipes
# GET /recipes.json
def index
@recipes = current_user.recipes
end
# GET /recipes/1
# GET /recipes/1.json
def show
end
# GET /recipes/new
def new
@recipe = current_user.recipes.build
end
# GET /recipes/1/edit
def edit
end
# POST /recipes
# POST /recipes.json
def create
@recipe = current_user.recipes.build(recipe_params)
respond_to do |format|
if @recipe.save
format.html { redirect_to @recipe, notice: 'Recipie was successfully created.' }
format.json { render :show, status: :created, location: @recipe }
else
format.html { render :new }
format.json { render json: @recipe.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /recipes/1
# PATCH/PUT /recipes/1.json
def update
respond_to do |format|
if @recipe.update(recipe_params)
format.html { redirect_to @recipe, notice: 'Recipie was successfully updated.' }
format.json { render :show, status: :ok, location: @recipe }
else
format.html { render :edit }
format.json { render json: @recipe.errors, status: :unprocessable_entity }
end
end
end
# DELETE /recipes/1
# DELETE /recipes/1.json
def destroy
@recipe.destroy
respond_to do |format|
format.html { redirect_to recipes_url, notice: 'Recipie was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_recipe
@recipe = current_user.recipes.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def recipe_params
params.fetch(:recipe, {...})
end
end