Ruby on rails (params[:id])在方法调用后更改
我试图在我的控制器中调用一个方法来更改对象的布尔值。基本上,用户单击“验证”,这称为:Ruby on rails (params[:id])在方法调用后更改,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,我试图在我的控制器中调用一个方法来更改对象的布尔值。基本上,用户单击“验证”,这称为:verify\u business\u path(b) 我在URL users/id/dashboard上。根据日志,它传递正确的ID并调用URL/ID/verify。这两个URL中的ID不同。然后调用验证方法: def verify @business = Business.find(params[:id]) if current_user.admin? @business.update_
verify\u business\u path(b)
我在URL users/id/dashboard上。根据日志,它传递正确的ID并调用URL/ID/verify。这两个URL中的ID不同。然后调用验证方法:
def verify
@business = Business.find(params[:id])
if current_user.admin?
@business.update_attribute(:verified, true)
if @business.save
redirect_to dashboard_user_path(current_user.id)
else
redirect_to destroy_user_session
end
end
# save, render, etc
end
得到的ID是错误的。它获取用户ID,而不是您在日志中看到的业务ID:
Started GET "/businesses/30/verify" for 127.0.0.1 at 2013-07-10 15:22:20 +0100
Processing by BusinessesController#verify as HTML
Parameters: {"id"=>"30"}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = 13 LIMIT 1
Redirected to http://localhost:3000/users/13/dashboard
Filter chain halted as :check_if_admin rendered or redirected
Completed 302 Found in 4ms (ActiveRecord: 0.6ms)
如何获得使用业务ID而不是用户ID的验证方法
谢谢
编辑:
您可以在日志中看到,它在第3行传递了正确的参数(业务ID),但在第4行使用错误的参数(当前用户ID)运行了查询。根据您的日志,由于
check\u if\u admin
操作中的重定向,验证操作从未执行,这很可能是在过滤器之前的中调用的
您可以通过删除过滤器之前的检查\u if\u admin
来确保执行验证
。如果要保留的功能,请检查\u If\u admin
,然后将其添加到条件中:
# app/controllers/businesses_controller.rb
def verify
@business = Business.find(params[:id])
if current_user.admin?
@business.update_attribute(:verified, true)
if @business.save
redirect_to dashboard_user_path(current_user.id)
else
redirect_to destroy_user_session
end
else # If user is not an admin
# Logic from `check_if_admin`
end
# save, render, etc
end
关于您的编辑,日志实际上是正确的<代码>参数:{“id”=>“30”}
表示业务id作为参数传递,并且用户加载(0.6ms)从“用户”中选择“用户”。*其中“用户”。“id”=13 LIMIT 1
表示要查找当前用户
过滤器链已暂停:检查\u如果\u admin呈现或重定向
这意味着您的验证方法没有在\u过滤器之前执行自身检查
methods@Salil你说得对,我去掉了那个过滤器,它工作了。我知道现在发生了什么:)我的用户是管理员,但在verify方法执行之前,before_筛选器正在重定向。谢谢你的帮助。如果你回答这个问题,我会选择正确的。@salil我使用这个过滤器和另一个过滤器将用户和管理员重定向到正确的“主页”。有什么方法可以让我在必要的时候调用验证方法吗?@zeantsoi我刚刚接受了你的回答。这是正确的,我只是给了Salil一个发布答案的机会,因为他在评论中首先得到了正确的答案。谢谢你的帮助!