how to call a active record named scope with a string

后端 未结 4 1366
梦谈多话
梦谈多话 2021-02-20 14:19

I\'m sure I\'m miss understanding the use of call but I thought I could do something like this.

@case_studies = CaseStudy.call(\"some_named_scope\")


        
相关标签:
4条回答
  • 2021-02-20 14:44

    If I understand what you mean, that's what you should call it:

    @case_studies = CaseStudy.send(:some_named_scope)
    

    You can use send to call a method and pass either a symbol or a string to it.

    0 讨论(0)
  • 2021-02-20 14:53

    Although @kolrie has the correct answer, it is not safe at all.

    It should be whitelisted as follows:

    scope = ["first_scope", "second_scope", "default_scope"].include? params[:action] ? params[:scope] : "default_scope"
    @case_studies = CaseStudy.send(scope)
    
    0 讨论(0)
  • 2021-02-20 15:05

    If some_named_scope is a named_scope of the CaseStudy model, you can use send to call the method corresponding to params[:action] value. But this is obviously heavily exploitable.

    So, security aside, you could get going with:

    @case_studies = CaseStudy.send(params[:action])
    

    Hope it works.

    0 讨论(0)
  • 2021-02-20 15:11

    To have an extra layer of security on top of the whitelisting BookOfGreg suggested, use public_send instead of send, it'll only work calling methods of the public interface, while send can reach even private methods.

    So:

    CaseStudy.public_send(:some_scope)

    0 讨论(0)
提交回复
热议问题