-->

rails - find with condition in rails 4

2020-08-02 06:59发布

问题:

I recently upgraded my rails to Rails 4.1.6.

This query used to work :

@user = User.find(:all, :conditions => { :name => 'batman' })

Now I get this error message:

Couldn't find all Users with 'id': (all, {:conditions=>{:name=>"batman"}}) (found 0 results, but was looking for 2)

When I check the logs I can see that rails is trying to do a completely different query :

User Load (0.4ms)  SELECT "users".* FROM "users"  WHERE "users"."id" IN ('all', '---
:conditions:
  :name: batman
')

It looks like, it's trying to get all the users with the id "all" and "{:conditions=>{:name=>"batman"}}". Please help.

UPDATE:

My real question behind that was I want to get a specific user and add to it his cars, only the cars that are blue. For example this is my query, the user id is 20.

@user = User.joins(:cars).find(20, :cars => {:color => "blue"})

But I get this error:

Couldn't find all Users with 'id': (20, {:cars=>{:color=>"blue"}}) (found 41 results, but was looking for 2)

回答1:

You should definitely read this ActiveRecord Query Interface quide

User.where(name: "batman")



回答2:

Some others already pointed out: The query syntax changed. Try this:

@user = User.joins(:cars).where(:cars => { :color => "blue" }).find(20)

Note that this will raise an exception if that record is not found, to return an array empty instead call:

@user = User.joins(:cars).where(:id => 20, :cars => { :color => "blue" })

I suggest to read: http://guides.rubyonrails.org/active_record_querying.html


If you want to load the user even if he does not have any cars and than display only his blue cars, I would do it like this:

@user = User.find(20)              # returns the user
@user.cars.where(:color => 'blue') # returns the user's blue cars (or an empty array)


回答3:

The find method is deprecated in this version of Rails (see the reference). Instead, you must use the where method.

In your case, you should write @user = User(:name => 'batman') or @user = User(name: 'batman')