2017-01-21 4 views
-1

Я создаю базовое рубиновое приложение для рельсов, подобное zapier или ifttt. Пользователи создают рецепты. Я бы хотел ТОЛЬКО отображать рецепты, созданные пользователем.Ruby on rails - Devise - Показать только созданный контент пользователя

Я использовал жемчужину устройства для аутентификации.

Мои вопросы:

я добавить "если user_signed_in?" в верхней части каждой страницы? Могу ли я добавить выше выход на макеты приложений? Есть ли способ лучше?

Могу ли я встраивать рецепты внутри пользователей?

+1

Показать код, который вы пробовали до сих пор. – 31piy

ответ

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 
+0

Спасибо. Это сработало! –