2013-07-27 2 views
0

У меня есть Listings Controller, где пользователи могут создавать свои объявления.Current_user в контроллере для Rails 4

Чтобы запретить пользователям редактировать другие пользователи списки я просто должен был обновить все действия от

Listing to current_user.listings 

но с Rails 4 контроллер был изменен и я не могу найти, как установить это.

My Controller File->

class ListingsController < ApplicationController 
    before_action :set_listing, only: [:show, :edit, :update, :destroy] 
    before_filter :authenticate_user!, :only => [:index] 

    # GET /listings 
    # GET /listings.json 
    def index 
    @listings = Listing.all 
    end 

    # GET /listings/1 
    # GET /listings/1.json 
    def show 
    end 

    # GET /listings/new 
    def new 
    @listing = Listing.new 
    end 

    # GET /listings/1/edit 
    def edit 
    end 

    # POST /listings 
    # POST /listings.json 
    def create 
    @listing = Listing.new(listing_params) 

    respond_to do |format| 
     if @listing.save 
     format.html { redirect_to @listing, notice: 'Listing was successfully created.' } 
     format.json { render action: 'show', status: :created, location: @listing } 
     else 
     format.html { render action: 'new' } 
     format.json { render json: @listing.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # PATCH/PUT /listings/1 
    # PATCH/PUT /listings/1.json 
    def update 
    respond_to do |format| 
     if @listing.update(listing_params) 
     format.html { redirect_to @listing, notice: 'Listing was successfully updated.' } 
     format.json { head :no_content } 
     else 
     format.html { render action: 'edit' } 
     format.json { render json: @listing.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /listings/1 
    # DELETE /listings/1.json 
    def destroy 
    @listing.destroy 
    respond_to do |format| 
     format.html { redirect_to listings_url } 
     format.json { head :no_content } 
    end 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_listing 
     @listing = Listing.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def listing_params 
     params.require(:listing).permit(:title, :description) 
    end 
end 

Любой знает решение?

ответ

3

изменить с #new на сборку. Таким образом, изменить все @listing = Listing.new к:

@listing = current_user.listings.build 

Затем в set_listing изменения в:

@listing = current_user.listings.find(params[:id]) 
+0

Вы БОГ !!! Спасибо –

+0

На самом деле это дает мне проблему, когда другой пользователь пытается просмотреть листинг -> ActiveRecord :: RecordNotFound в DisplayController # show. Не удалось найти Список с id = 13 [WHERE "listings". "User_id" =?] –

+0

Разве это не так? Как вы хотите, чтобы это функционировало? –

Смежные вопросы