如何在 Ruby On Rails 中使用内连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12702506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use inner join in Ruby On Rails
提问by suresh.g
I am working on rails.
我在铁路上工作。
my need is,
我的需要是,
@accountUrl = Account.find_by_id(current_account_id)
@details = Detail.find_by_acc_id(@accountUrl.id)
How to write inner join query from above example
如何从上面的例子中编写内部连接查询
Can any one.
任何一个都可以。
回答by rewritten
In this simple case Rails does not use a join, it joins "in code":
在这个简单的例子中,Rails 不使用连接,它“在代码中”连接:
Account.includes(:details).where(:id => current_account_id).first
It will make two separate queries.
它将进行两个单独的查询。
If you need a condition for the select, you have to join "by hand" (or through a scope)
如果您需要选择条件,则必须“手动”(或通过范围)加入
Account.joins(:details).where("details.name" => selected_detail).first
This will make an INNER JOIN and return only accounts satistfying the conditions.
这将进行 INNER JOIN 并仅返回满足条件的帐户。
回答by prasad.surase
model A
has_many :bs
model B
has_many :cs
in model A, u can write
在模型 A 中,你可以写
has_many :cs, :through => :bs #uses inner join to fetch the records.
check out http://guides.rubyonrails.org/active_record_querying.htmland http://asciicasts.com/episodes/215-advanced-queries-in-rails-3
查看http://guides.rubyonrails.org/active_record_querying.html和http://asciicasts.com/episodes/215-advanced-queries-in-rails-3
回答by Alexander Svetly
INNER JOIN is by default in Rails Example from Rails doc
在Rails 文档中的 Rails 示例中默认为 INNER JOIN
User.joins(:posts)
=> SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
In your case it will be something like that:
在您的情况下,它将是这样的:
Account.joins(:details)
.where(id: current_account_id)

