首页 文章

如何在rails中使用连接查询?

提问于
浏览
0

我有两个模型Client和Project .

型号

class Project < ApplicationRecord
    belongs_to :client
end
class Client < ApplicationRecord
    has_many :projects
end

我在客户端和项目表中有以下记录:

我想显示一个带有客户端名称的项目记录 . 我的控制器需要什么查询?

控制器

class ProjectsController < ApplicationController
  def index
    @projects = #your query here
  end
end

3 回答

  • 0

    我假设您的rails版本> 5

    class ProjectsController < ApplicationController
        def index
            @projects = Project.left_outer_joins(:client).select("projects.*, clients.name as client_name").group("projects.id")
        end
    end
    

    使用上面的查询,您将在单个项目 client_name 中获得另一个属性,其中包含项目's client name. If you want to do on application level You can go with ray'的答案,如果您想在数据库级别上执行,则可以在上面查询

  • 2

    在模型中做以下

    class Project < ApplicationRecord
    
        belongs_to :client
    
        delegate :client_name, to: :client
    
    end
    

    为了避免控制器中的N 1查询,

    class ProjectsController < ApplicationController
        def index
            @projects = Project.includes(:client)
        end
    end
    

    现在,您可以像Project对象一样调用 project.client_name

  • 0

    我认为没有理由使用 JOIN 查询 . 但我建议使用includes来避免N 1查询 .

    # in your controller
    @projects = Project.includes(:client)
    
    # in your view (simplified – without html tags)
    <% @projects.each do |project| %>
      <%= project.name %>
      <%= project.client.client_name %>
    <% end %>
    

相关问题