如何在Ruby On Rails中使用内连接

我正在铁轨上工作。

我的需要是,

@accountUrl = Account.find_by_id(current_account_id) @details = Detail.find_by_acc_id(@accountUrl.id) 

如何从上面的例子中编写内连接查询

可以任何一个。

在这个简单的例子中,Rails不使用连接,它加入“在代码中”:

 Account.includes(:details).where(:id => current_account_id).first 

它将进行两个单独的查询。

如果您需要选择条件,则必须“手动”(或通过范围)加入

 Account.joins(:details).where("details.name" => selected_detail).first 

这将使INNER JOIN成为仅返回满足条件的帐户。

 model A has_many :bs model B has_many :cs 

在模型A中,你可以写

 has_many :cs, :through => :bs #uses inner join to fetch the records. 

查看http://guides.rubyonrails.org/active_record_querying.html和http://asciicasts.com/episodes/215-advanced-queries-in-rails-3

默认情况下,INNER JOIN是Rails doc中的Rails示例

 User.joins(:posts) => SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id" 

在你的情况下,它将是这样的:

 Account.joins(:details) .where(id: current_account_id)