简体   繁体   English

如何在Ruby On Rails中使用内部联接

[英]How to use inner join in Ruby On Rails

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. 可以任何一个。

In this simple case Rails does not use a join, it joins "in code": 在这个简单的例子中,Rails不使用连接,它加入“in code”:

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成为仅返回满足条件的帐户。

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.html and http://asciicasts.com/episodes/215-advanced-queries-in-rails-3 查看http://guides.rubyonrails.org/active_record_querying.htmlhttp://asciicasts.com/episodes/215-advanced-queries-in-rails-3

INNER JOIN is by default in Rails Example from Rails doc 默认情况下,INNER JOIN是Rails doc中的Rails示例

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM