与之间的关系,并发现其中的差异 [英] Difference Between find and Where with Relationships

查看:113
本文介绍了与之间的关系,并发现其中的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不认为是有区别的,当涉及到活动记录和查找数据。

I wouldn't think there is a difference when it comes to active record and finding data.

下面是我的模型

class User < ActiveRecord::Base
  has_many :shows
end

class Show < ActiveRecord::Base
  belongs_to :user
end

在我使用的铁轨控制台我可以做以下和它的作品。

When I use the rails console I can do the following and it works.

u = User.find(1)
u.shows

这给了我全部显示该用户。

It gives me all the shows for that user.

然而,当我这样做

u = User.where("username = ?", "percent20")
u.shows # this is doesn't work gives me a now instance error

我得到同样的用户和相关的信息,但没有关系。我可以看到的唯一的问题也许是我做错了什么,因为之间有一定区别在哪里找到。

I get the same user and relevant information, but not the relationship. The only problem I can see is maybe I am doing something wrong because there is some difference between where and find.

任何帮助是AP preciated。

Any help is appreciated.

推荐答案

现在的问题是不是关系。

The problem is not the relationship.

 u = User.find(1) 

返回一个User

returns one User

 #return a Set of users. In your case its only one user.
 u = User.where("username = ?", "percent20") 

结果类型的ActiveRecord ::关系 - > [用户,用户,用户]

The result type is ActiveRecord::Relation --> [User, User, User]

使用如率先拿到了第一个用户

use e.g. first to get the first User

 #returns the first user
 u = User.where("username = ?", "percent20").first

u.class.name =>用户

u.class.name => "User"

这篇关于与之间的关系,并发现其中的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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