how to call a active record named scope with a string

梦想与她 提交于 2019-12-10 03:07: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")

Where "some_named_scope" is also a named scope in CaseStudy. The reason why I need to use call is because I have named scopes that are the same names of the actions in the controller so I'm hopping to do something like this.

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

EDIT

Forgive me, I just realized I was thinking about the send method, some how the word call got stuck in my head. But @case_studies = CaseStudy.send(params[:action]) works as I thought it would.


回答1:


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.




回答2:


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)



回答3:


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.



来源:https://stackoverflow.com/questions/13317056/how-to-call-a-active-record-named-scope-with-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!