0

I have two models Client and Project.

Models

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

I have the following records inside the clients and projects tables:

enter image description here

enter image description here

I want to display the an project record with the client name. What query do I need in my controller?

Controller

class ProjectsController < ApplicationController
  def index
    @projects = #your query here
  end
end
2
  • 2
    You tagged your question all Rails versions from 3 to 5. What version do you actually use? Dec 10, 2018 at 8:10
  • If the Rails version is not relevant to the question I suggest removing all Ruby on Rails version tags.
    – 3limin4t0r
    Dec 10, 2018 at 9:41

2 Answers 2

3

I see no reason to use a JOIN query. But I would suggest using includes to avoid N+1 queries.

# 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 %>
1
  • 3
    Note: Keep in mind that this code raises "NoMethodError: undefined method `client_name' for nil:NilClass" if client can be nil. In this case check for the presence of client first, or use the safe navigation operator (&.).
    – 3limin4t0r
    Dec 10, 2018 at 10:00
1

I am assuming your rails versions is > 5

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

With above query you will get one another attribute in single project client_name which will contain project's client name. If you want to do on application level You can go with ray's answer, if you want to do on database level, you can write above query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.