如何在ActiveRecord中执行此类连接表?

时间:2014-04-21 18:03:55

标签: sql ruby-on-rails rails-activerecord

使用ActiveRecord关系模型进行以下连接时需要帮助:

select "access_urls"."id", "controller_urls"."controller", "action_urls"."action" from
"access_urls"
inner join "controller_urls"
on "controller_urls"."id" = "access_urls"."controller_url_id"
inner join "action_urls"
on "action_urls"."id" = "access_urls"."action_url_id"

我有AccessUrl,ActionUrl和ControllerUrl模型

class AccessUrl < ActiveRecord::Base
  belongs_to :controller_url
  belongs_to :action_url
end

class ActionUrl < ActiveRecord::Base
  has_many :access_urls
  validates :action, presence: true, uniqueness: { message: "já encontra-se em uso." }
end

class ControllerUrl < ActiveRecord::Base
  has_many :access_urls
  validates :controller, presence: true, uniqueness: { message: "já encontra-se em uso." }
end

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

使用joins

result = AccessUrl.joins(
  :controller_url, :action_url
).select(
  'access_urls.id, controller_urls.control, action_urls.action'
)

这将为您提供包含result对象的AccessUrl关系。您可以遍历result并访问所选列:

result.each do |r| 
  # r.id
  # r.control
  # r.action
end