阻止不同的用户通过show方法查看模型

时间:2017-07-12 20:34:39

标签: ruby-on-rails

在我的每个模型的索引方法中,我确保从当前用户开始查询:current_user.model.all,以便仅显示属于当前用户的模型。

我的所有模型的show方法非常简单和标准,没有current_user。

  def show
    @logica = Logica.find params[:id]
    authorize @logica
  end

这确实打开了用户在网址中输入随机ID并从其他用户查看模型的机会。防止这种情况发生的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

has_many关联提供了多种不同的方法,包括find

current_user.model.find(params[:id])

类似于

Model.where(user_id: current_user.id).find(params[:id])

如果您必须浏览多个模型才能访问您的用户模型,例如

class User < ApplicationRecord
  has_one :test_one
end

class TestOne < ApplicationRecord
  has_one :test_three
  belongs_to :user
end

class TestThree < ApplicationRecord
  has_many :test_fours
  belongs_to :test_one
end

class TestFour < ApplicationRecord
  belongs_to :test_three
end

您可以通过执行类似

的操作在单个查询中进行设置
TestFour.joins(:test_three => { :test_one => :user }).where(test_threes: { test_ones: { users: { id: current_user.id}}}).find(1)
#  TestFour Load (1.2ms)  SELECT  "test_fours".* FROM "test_fours" INNER JOIN "test_threes" ON "test_threes"."id" = "test_fours"."test_three_id" INNER JOIN "test_ones" ON "test_ones"."id" = "test_threes"."test_one_id" INNER JOIN "users" ON "users"."id" = "test_ones"."user_id" WHERE "users"."id" = $1 AND "test_fours"."id" = $2 LIMIT $3  [["id", 1], ["id", 1], ["LIMIT", 1]]
#=> #<TestFour id: 1, test_three_id: 1, created_at: "2017-07-12 21:06:51", updated_at: "2017-07-12 21:06:51">

然后如果您使用用户ID / test四个ID匹配的话来执行此操作:

TestFour.joins(:test_three => { :test_one => :user }).where(test_threes: { test_ones: { users: { id: current_user.id + 1}}}).find(1)
#  TestFour Load (0.8ms)  SELECT  "test_fours".* FROM "test_fours" INNER JOIN "test_threes" ON "test_threes"."id" = "test_fours"."test_three_id" INNER JOIN "test_ones" ON "test_ones"."id" = "test_threes"."test_one_id" INNER JOIN "users" ON "users"."id" = "test_ones"."user_id" WHERE "users"."id" = $1 AND "test_fours"."id" = $2 LIMIT $3  [["id", 2], ["id", 1], ["LIMIT", 1]]
#=> ActiveRecord::RecordNotFound: Couldn't find TestFour with 'id'=1 [WHERE "users"."id" = $1]