[英]Ruby on Rails: “SELECT” MySQL command
I'm writing an application using MySQL. 我正在使用MySQL编写应用程序。 There's a table called "Requests".
有一个名为“请求”的表。
That table has a field "user_id" from Table "Users". 该表具有表“ Users”中的字段“ user_id”。
I'd like to select all requests from a user_id
. 我想从
user_id
选择所有请求。
For example: 例如:
SELECT * FROM requests WHERE user_id = ("the id I want");
How can I do that using Ruby language, and not an SQL string? 如何使用Ruby语言而不是SQL字符串来做到这一点?
在ActiveRecords中,其操作如下:
Request.where(user_id: ID)
There are a few different ways, as you can see from @shivam and @amalrik's answers. 从@shivam和@amalrik的答案中可以看出,有几种不同的方法。 It also depends on the ORM you're using.
它还取决于您使用的ORM。 If you're using Rails out of the box, you're probably using ActiveRecord .
如果您直接使用Rails,则可能是使用ActiveRecord 。
Probably the most idiomatic way is to have the correct associations on your User
and Request
models. 可能最惯用的方法是在
User
模型和Request
模型上具有正确的关联 。
in app/models/user.rb
: 在
app/models/user.rb
:
class User < ActiveRecord::Base
has_many :requests
end
and app/models/request.rb
: 和
app/models/request.rb
:
class Request < ActiveRecord::Base
belongs_to :user
end
This would allow you to find a user and call its #requests
method: 这将使您能够找到用户并调用其
#requests
方法:
User.find(user_id).requests
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.