简体   繁体   English

在rails控制台中无范围工作但在控制器操作中无效

[英]Unscoped work in rails console but not work in controller action

I have model with default_scope: 我有default_scope的模型:

class Campaign < ActiveRecord::Base
  default_scope where("campaigns.status != ?", "archive")
end

Then I need disable this scope in show action: 然后我需要在show action中禁用此范围:

@campaign = Campaign.unscoped.find(params[:id])

But I see Couldn't find Campaign with id=1 [WHERE (campaigns.status != 'archive')] 但我看到Couldn't find Campaign with id=1 [WHERE (campaigns.status != 'archive')]

Then I tried the same solution in rails console: 然后我在rails控制台中尝试了相同的解决方案:

 Campaign.unscoped.find(1)
 SELECT `campaigns`.* FROM `campaigns` WHERE `campaigns`.`id` = 1 LIMIT 1 

And all works fine, what I doing wrong in controller? 一切正常,我在控制器中做错了什么?

UPDATE: 更新:

Campaign.unscoped{ } Campaign.unscoped {}

Did not work too. 也没用。 It seems @campaign determined elsewhere and earlier, because I delete all rows from my show action and now it looks like: 似乎@campaign在其他地方和之前确定过,因为我从show动作中删除了所有行,现在它看起来像:

def show
end

And I am still getting this error: Couldn't find Campaign with id=1 [WHERE (campaigns.status != 'archive')] 我仍然收到此错误: Couldn't find Campaign with id=1 [WHERE (campaigns.status != 'archive')]

I find out this tricks in load_and_authorize_resource , but how can I fix it? 我在load_and_authorize_resource找到了这个技巧,但我该如何解决呢?

Ref this 参考这个

Campaign.unscoped {
  Campaign.find(params[:id]) 
}

It seems like what you have would work fine, according to the documentation. 根据文档,看起来你的工作会很好。 However, it is mentioned here that it is recommended to use the block form of unscoped. 但是, 这里提到建议使用无结构的块形式。 You might give that a try and see if it resolves the problem. 您可以尝试一下,看看它是否能解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM