轨道 - 找到条件在轨道4 [英] rails - find with condition in rails 4

查看:168
本文介绍了轨道 - 找到条件在轨道4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近将rails升级到了Rails 4.1.6。
$ b 这个查询用于工作:

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

现在我得到这个错误信息:

$ $ $ $ $ $ $ $ $ $找不到全部使用'id'的用户:(all,{:conditions => {:name =>batman}})(找到0结果,但是正在寻找2)
/ pre>

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

<$用户负载(0.4ms)SELECTusers。* FROMusersWHEREusers。idIN('all','---
:conditions :
:name:batman
')

让所有的用户ID为全部和{:conditions => {:name =>蝙蝠侠}}。请帮助。

UPDATE:



我真正的问题是我想获得一个特定的用户并添加给他的车,只有蓝色的车。例如,这是我的查询,用户ID是20。
$ b $ $ p $ @user = User.joins(:cars).find( 20,:cars => {:color =>blue})

这个错误:
$ b


找不到所有用户都是'id':(20,{:cars => {:color =>蓝色}})
(找到41个结果,但是正在寻找2)


解决方案

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

$ p $ @user = User.joins(:cars).where(:cars => {:color => ;blue})。find(20)

注意,如果该记录会引发异常没有找到,返回一个空数组而不是调用:

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

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






如果你想加载用户,即使他没有任何汽车,也不能显示他的蓝色汽车,它是这样的:

$ p $ @user = User.find(20)#返回用户
@ user.cars。其中(:color =>'blue')#返回用户的蓝色汽车(或一个空的数组)


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)

解决方案

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)

这篇关于轨道 - 找到条件在轨道4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆