ruby-on-rails - 授权查询不起作用的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
解决方案
这条线
Offer.where(id: params[:id], user_id: current_user.id)
将始终评估为,true
因为它返回一个ActiveRecord::Relation
- 即使关系评估为一个空数组。因此,您的方法永远不会触发重定向。
相反,请使用评估为true
或false
类似的方法ActiveRecord.exists?
:
Offer.exists?(id: params[:id], user_id: current_user.id)
推荐阅读
- php - Laravel:如何在注销时刷新会话和重定向?
- angularjs - 如何根据季度显示存储库中的数据?
- excel - VBA Shapes.AddTextbox 自定义布局
- python-3.x - 使用 AWS lambda 将自定义指标数据写入 CloudWatch 时超时
- c++ - 如何告诉声明为的数组的元素计数:std::unique_ptr
- pyinstaller - 运行 pyinstaller 后找不到模块
- sql - 更新查询、嵌套 iif SET 和连接表
- javascript - TypeError: is null 因为目标文件在包含
- python - 我正在尝试获取标签名称数组以进行可视化,我需要在代码下方运行但遇到问题。各位大佬可以在下面给我建议吗?
- r - 在 R 中打印没有前面方括号的结果