2017-01-21 18 views
-1

我正在創建一個類似於zapier或ifttt的rails應用程序的基本ruby。用戶創建食譜。我只想顯示用戶創建的食譜。紅寶石軌道 - 設計 - 僅顯示用戶創建的內容

我已經使用設備gem進行驗證。

我的問題:

我是否添加「if user_signed_in?」在每個頁面的頂部?我可以在應用程序佈局上添加以上收益率嗎?有沒有更好的辦法?

我是否在用戶中嵌套食譜?

+1

顯示目前爲止您嘗試過的一些代碼。 – 31piy

回答

0

假設你有一個具有用戶和配方

你可以做這樣的事情之間有很多關聯。使用devise提供的current_user helper,並使用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 
+0

謝謝。這工作! –