Rails 3使用连接选择SQL查询

时间:2011-09-12 19:19:43

标签: mysql ruby-on-rails ruby-on-rails-3

选择fonction和join时遇到问题。

这是我当前的查询。

@search = Building.joins('INNER JOIN "floors" ON "floors"."building_id" = "buildings"."id" INNER JOIN "spaces" ON "spaces".floor_id = "floors".id')

但是我希望在我的选择中有更多选项来使用floors.number,space.number我试过这个

@search = Building.select('buildings.name, floors.number, spaces.number).joins('INNER JOIN "floors" ON "floors"."building_id" = "buildings"."id" INNER JOIN "spaces" ON "spaces".floor_id = "floors".id')

在我看来,我得到了错误......这是我的观点

<% for b in @building do %>

<div style='width:100%;margin-left:auto;margin-right:auto;margin-top:5px;'>

    <div style="float:left;width:50%"><%= b.name %></div>
    <div><%= link_to 'view', building_path(b) %></div>

</div>

<% end %>

这是我得到的错误

ActionController::RoutingError in Search_engine#show

Showing /Users/stephanebaribeau/Sites/cadifice/app/views/search_engine/show.html.erb where line #21 raised:

No route matches {:action=>"show", :controller=>"buildings", :id=>#<Building name: "gigi">}

Extracted source (around line #21):

18:     <div style='width:100%;margin-left:auto;margin-right:auto;margin-top:5px;'>
19:     
20:         <div style="float:left;width:50%"><%= b.name %></div>
21:         <div><%= link_to 'view', building_path(b) %></div>
22:         
23:     </div>
24: 

感谢

在我的选择中添加building.id,floors.id和spaces.id后,我尝试显示floors.number和spaces.number

<%= debug @building %>

给我

[#<Building id: 9, name: "234234">]

我不知道为什么我只有2个元素,也许是因为select是在Building.select上?

感谢

- 更新14/09

这是我的新控制器

  @search = Building.select('buildings.id, buildings.slug, floors.id, spaces.id, buildings.name, floors.number, spaces.number').joins('INNER JOIN floors ON floors.building_id = buildings.id INNER JOIN spaces ON spaces.floor_id = floors.id')
  @search = @search.where("buildings.name like '%#{params[:building_name]}%'") if !params[:building_name].blank?
  #@search = @search.where("buildings.name like ?", params[:building_name]) if !params[:building_name].blank?
  if params[:space_type].present?
    @search = @search.where("spaces.space_type_id = ?", params[:space_type][:space_type_id]) if !params[:space_type][:space_type_id].blank?
  end
  @search = @search.where("floors.min_net_rent >= #{params[:floor_min_rent]}") if !params[:floor_min_rent].blank?
  @search = @search.where("floors.max_net_rent <= #{params[:floor_max_rent]}") if !params[:floor_max_rent].blank?

  @building = @search

我现在遇到的问题是调试给我的问题。只有2个领域的建筑物。是因为Building.select?我怎样才能进入我的选择领域?

感谢。

2 个答案:

答案 0 :(得分:2)

看看你的代码:

Building.select('buildings.name, floors.number, spaces.number)...

你没有选择建筑物id,所以当有时间检索时,Rails有点丢失。

答案 1 :(得分:2)

你可以这样做...... 希望它有用

@search = Building.select("buildings.name, floors.number, spaces.number").joins("INNER JOIN floors ON floors.building_id = buildings.id INNER JOIN spaces ON spaces.floor_id = floors.id")