Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用SQL外键约束停止Rails用户操作_Sql_Ruby On Rails - Fatal编程技术网

使用SQL外键约束停止Rails用户操作

使用SQL外键约束停止Rails用户操作,sql,ruby-on-rails,Sql,Ruby On Rails,您好,我的SQL和/或Rails朋友 假设我们有两个模型: class Hostel < ActiveRecord::Base has_many :beds end class Bed < ActiveRecord::Base belongs_to :hostel end 编辑: 这里有一个更好的问题: 在Rails中,我可以打开控制台并手动创建新的预订: Booking.new(user_id: 1, bed_id: 12, start: "2017-10-13", e

您好,我的SQL和/或Rails朋友

假设我们有两个模型:

class Hostel < ActiveRecord::Base
  has_many :beds
end

class Bed < ActiveRecord::Base
  belongs_to :hostel
end
编辑: 这里有一个更好的问题:

在Rails中,我可以打开控制台并手动创建新的预订:

Booking.new(user_id: 1, bed_id: 12, start: "2017-10-13", end: "2017-10-15")

数据库将创建记录,即使ID为12的床不属于用户1。有没有办法让SQL强化这些约束?

我知道这并不完全是我们所要求的,但是。。。 我的首选解决方案是在rails中实现,它提供了更好的控制,并且与平台无关

(很抱歉,我无法轻松验证这一点,但它应该能让您了解这一点)

class BookingsController
您如何知道哪些床属于用户?他的@OscarLuza。每个床记录都有一个用户id外键。如果一个ID=4的用户“Hostel Panama”试图使用bed ID:12、user_ID:6(另一家旅馆)创建预订,我希望SQL停止该操作。嗨,Andy。我喜欢您的解决方案,但它仍然将代码保留在控制器中。这就是我的if@床所做的。我只是想知道,如果一个外键与另一个外键不匹配,是否有一些纯SQL可以拒绝插入。嗨,Patrick,基于不同的数据库技术会有不同的实现。假设您的数据库支持触发器,那么这应该是可能的。但你的建议是,你也不相信“当前用户”是正确的——在这种情况下,你有一个更大的问题。嗨,安迪。谢谢你的回复。我需要它的唯一真正原因是确保登录用户不会使用DevTools破解bed_id号。因为只有登录用户的床位才对他们有效,所以在正常使用期间不应该发生这种情况。
INSERT INTO bookings (start_date, end_date, bed_id, user_id)
VALUES ("2017-10-13", "2017-10-15", 12, 1)
UNLESS (SELECT * FROM beds WHERE id = 12).user_id != current_user.id

# what I'm doing above is verifying that bed #12 has a user_id that 
# is the same as the current user's ID. That way, if a user 
# manipulates the params, SQL catches it.
Booking.new(user_id: 1, bed_id: 12, start: "2017-10-13", end: "2017-10-15")
class BookingsController < ApplicationController

before_action :check_authorisation, only: :create

def check_authorisation
    unless current_user.beds.where(id: params[:bed_id]).first
        flash[:danger] = "You are not authorised to access this section"
        redirect_to home_url # halts request cycle need to adjust home_url to appropriate
    end
end