首页 > 解决方案 > 授权查询不起作用的Rails

问题描述

我正在尝试为页面(显示)创建授权方法(offer_authorised)。不幸的是,where 查询似乎无法与我拥有的代码一起正常工作。

我仍然可以访问所有用户的页面,尽管我应该只能在 user_id 等于当前用户 id 时才能访问它。

Offer.where("id = ? AND user_id = ?", 2, 2) 
  Offer Load (0.7ms)  SELECT "offers".* FROM "offers" WHERE (id = 2 AND user_id = 2) LIMIT $1  [["LIMIT", 11]]
 => #<ActiveRecord::Relation [#<Offer id: 2, amount: 950, status: "hyväksytty", rental_id: 1, user_id: 2, created_at: "2019-09-19 12:21:22", updated_at: "2019-09-21 11:08:52">]> 

在控制台方面,它似乎正确地返回了正确的记录。

这是我的优惠控制器。

class OffersController < ApplicationController
    before_action :authenticate_user!
    before_action :offer_authorised, only: [:show]
    before_action :set_offer, only: [:accept, :reject]
    before_action :is_authorised, only: [:accept, :reject]

    def create
        rental = Rental.find(offer_params[:rental_id])

        if rental && rental.user_id == current_user.id
            redirect_to request.referrer, alert: 'Et voi tehdä tarjousta omasta kohteestasi.'
        end

        if Offer.exists?(user_id: current_user.id, rental_id: offer_params[:rental_id])
            redirect_to request.referrer, alert: 'Voit tehdä vain yhden tarjouksen tällä hetkellä.'
        end

        @offer = current_user.offers.build(offer_params)
        if @offer.save
            redirect_to my_offers_path, notice: 'Tarjous tehty.'
        else
            redirect_to request.referrer, flash: {error: @offer.errors.full_messages.join(', ')}
        end
    end

    def accept
        if @offer.odottaa?
            @offer.hyväksytty!
            @offer.rental.update(active: !@offer.rental.active?)
            flash[:notice] = 'Tarjous hyväksytty.'
        end
        redirect_to request.referrer        
    end

    def reject
        if @offer.odottaa?
            @offer.hylätty!         
            flash[:notice] = 'Tarjous hylätty.'
        end
        redirect_to request.referrer    

    end

    def show
        @offer = Offer.find(params[:id])
        @rental = @offer.rental_id ? Rental.find(@offer.rental_id) : nil
    end


    private

    def offer_authorised
        redirect_to dashboard_path, 
            alert: "Sinulla ei ole oikeuksia" unless Offer.where(id: params[:id], user_id: current_user.id)
    end


    def set_offer
        @offer = Offer.find(params[:id])
    end

    def is_authorised
        redirect_to root_path, alert: "Sinulla ei ole tähän oikeuksia." unless current_user.id == @offer.rental.user_id
    end

    def offer_params
        params.require(:offer).permit(:amount, :rental_id, :status)
    end
end

标签: ruby-on-railsruby

解决方案


这条线

Offer.where(id: params[:id], user_id: current_user.id)

将始终评估为,true因为它返回一个ActiveRecord::Relation- 即使关系评估为一个空数组。因此,您的方法永远不会触发重定向。

相反,请使用评估为truefalse类似的方法ActiveRecord.exists?

Offer.exists?(id: params[:id], user_id: current_user.id)

推荐阅读