导轨 – 在导轨中找到条件4

我最近将我的rails升级到Rails 4.1.6。

此查询用于工作:

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

现在我收到此错误消息:

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

当我检查日志时,我可以看到rails正在尝试执行完全不同的查询:

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

看起来,它试图让所有用户都拥有ID“all”和“{:conditions => {:name =>”batman“}}”。 请帮忙。

更新:

我背后真正的问题是我想要一个特定的用户并添加他的汽车,只有蓝色的汽车。 例如,这是我的查询,用户ID是20。

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

但我得到这个错误:

找不到拥有’id’的所有用户:(20,{:cars => {:color =>“blue”}})(找到41条结果,但正在寻找2)

其他一些人已经指出:查询语法已更改。 试试这个:

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

请注意,如果找不到该记录,这将引发exception,将数组返回空而不是调用:

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

我建议阅读: http : //guides.rubyonrails.org/active_record_querying.html


如果你想加载用户,即使他没有任何汽车,只显示他的蓝色汽车,我会这样做:

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

你一定要阅读这个ActiveRecord Query Interface quide

User.where(name: "batman")

在此版本的Rails中不推荐使用find方法(请参阅参考资料 )。 相反,您必须使用where方法。

在你的情况下,你应该写@user = User(:name => 'batman')@user = User(name: 'batman')