rails - find with condition in rails 4

故事扮演 提交于 2019-12-04 20:35:56

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)

You should definitely read this ActiveRecord Query Interface quide

User.where(name: "batman")

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')

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