0

I saw warnings in my code that find is deprecated. However, I can't seem to make sense of what I should use to replace the find.

For example, I have the following:

 private
    # Use callbacks to share common setup or constraints between actions.
    def set_search
      @search = Search.find(params[:id])
    end

What would be the proper statement now?

Matouš Borák
  • 15,606
  • 1
  • 42
  • 53
Chris Mendla
  • 987
  • 2
  • 10
  • 25
  • 2
    find isn't deprecated, not in that way.... what is the error? – trh Apr 07 '16 at 17:58
  • I looked at something on github that says what you are saying. If I am correct `Note that find(primary_key), find_by..., and find_by...! are not deprecated.` would be saying that the way I am using Find is not deprecated. I think the error might be in my IDE (Rubymine) which is where I saw the warnings. [link](https://github.com/rails/activerecord-deprecated_finders) – Chris Mendla Apr 07 '16 at 18:02
  • 2
    Chris, this seems to be a bug in current Rubymine, see [this answer](http://stackoverflow.com/a/36481621/1544012). – Matouš Borák Apr 07 '16 at 18:26
  • Possible duplicate of ['ActiveRecord::Core::ClassMethods.find' call is deprecated](http://stackoverflow.com/questions/36480425/activerecordcoreclassmethods-find-call-is-deprecated) – Matouš Borák Apr 12 '16 at 10:41

1 Answers1

2

I don't think find method has been deprecated. But I think it will throw error on use find method as if passed params[:id] don't hold correct/existing record id, then it will throw error.

So it would be better to use where clause

@search = Search.where(:id => params[:id]).first
if @search
  #write the code here
end

instead

Sukanta
  • 585
  • 3
  • 6
  • 2
    I don't think it's a matter of secure/insecure. Sometime you want to use find(id) which raise ActiveRecord::ReordNotFound. In other case you want it to return nil when it doesn't find anything. Both ways are secure. You just have to know what each does and handle it correctly. – Reynard Apr 07 '16 at 18:28
  • 1
    by the way, instead of using where and first, you could also use ```Search.find_by(id: params[:id])``` which is more compact. Some style guide actually recommend that. – Reynard Apr 07 '16 at 18:30
  • 1
    As a side note in Rails 4.2, `.where(...).first` will add an implicit "ORDER BY id" to the SQL query. On large tables I've found this to really slow down the results. If you don't care about order (which you don't in this case) use `.where(...).take`. – jwadsack Apr 13 '16 at 17:48