根据某些标准设置default_scope
我试图根据由 ActionController before_filter 确定的一些标准来设置默认范围。在控制器中:
before_filter :authorize
...
def authorize
if some_condition
@default_scope_conditions = something
elsif another_condition
@default_scope_conditions = something_else
end
end
在 ActiveRecord 内部
default_scope :conditions => @default_scope_conditions
但它似乎不起作用,之前的过滤器被调用但 default_scope 没有设置。您能否告诉我我做错了什么以及如何解决它,或者建议我其他一些方法来实现这一目标。
I'm trying to set default scope according to some criteria determined by ana ActionController before_filter. In controller:
before_filter :authorize
...
def authorize
if some_condition
@default_scope_conditions = something
elsif another_condition
@default_scope_conditions = something_else
end
end
Inside the ActiveRecord
default_scope :conditions => @default_scope_conditions
But it doesn't seem to work, the before filter gets called but the default_scope doesn't get set. Could you please advise me what I'm doing wrong and how to fix it or suggest me some other way of achieving that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您设置了@default_scope_conditions - 这是来自控制器的实例变量,并且您希望从模型读取它。除非作为方法参数传递,否则它在模型中不可见。
此外,这种方法会打破将模型逻辑与控制器逻辑分开的 MVC 原则:您的模型不应自动访问有关控制器当前状态的信息。
你可以做什么:使用匿名范围。
然后,在您的方法中,您可以:
或
You set @default_scope_conditions - which is an instance variable from the controller and you expect to read it from the model. It is not visible from the model unless passed as method parameter.
More, this approach would break the MVC principle that separates the model logic from the controller logic: Your model shouldn't automatically access info about current state of the controller.
What you can do: use anonymous scopes.
Then, in your method, you can:
or
尝试使用一个 default_scope 并使用客户查找器覆盖它。
默认选项始终可以使用自定义查找器覆盖。
User.all # 将使用默认范围
User.all(:order => 'name desc') # 将使用传入的 order 选项。
然后你可以尝试类似
“No Check”的操作。
Try one default_scope and override it using custome finder.
The default options can always be overridden using a custom finder.
User.all # will use default scope
User.all(:order => 'name desc') # will use passed in order option.
Then you can try something like following
No Check though.