ruby-on-railsrubymodel-view-controlleractiverecordactioncontroller

With Ruby on Rails what's the best way to display data from a form field on a show page from another Ruby class?


I'm still somewhat new to Ruby and am having trouble displaying data on the show page from another class. I have two classes, Company and Job. On the Job show page I would like to display the Company's name, website and description from the Company form fields that created/posted the job when a job applicant views the respective job.

Was receiving an error when tinkering with the Job show controller action. Not entirely sure if the company is not being assigned an id when being created or if there's an issue with the show action login in the controller or a model association error on my end. Any help and explanation to resolve this issue is greatly appreciated.

Screenshot for Error Received on Job Show Page

Models

class Company < ApplicationRecord
  has_many :jobs
  has_many :job_applications, through: :jobs

class Job < ApplicationRecord
  belongs_to :user
  belongs_to :company, optional: true
  has_many :job_applications, dependent: :destroy

class JobApplication < ApplicationRecord
  belongs_to :user
  belongs_to :job

Controllers

class CompaniesController < ApplicationController
  
  private
    # Use callbacks to share common setup or constraints between actions.
    def set_company
      @company = Company.find(params[:id])
      # @company = self.create_company
    end

    # Only allow a list of trusted parameters through.
    def company_params
      params.require(:company).permit(:name, :website, :about, :user_id, :avatar)
    end



class JobsController < ApplicationController

   # GET /jobs/1 or /jobs/1.json
  def show
     @company = Company.find(params[:user_id])
  #  @company = Company.all
  #  @job = Job.find(params[:id])
  end

Routes

  resources :companies
  resources :jobs
  resources :jobs do
    resources :job_applications
  end

Job Show Page

  <%= @company.name %>
  <%= @company.website %>
  <%= @company.about %>

Solution

  • I believe the problem lies in your show method in the JobsController.

    It should look something like this:

    class JobsController < ApplicationController
    
       # GET /jobs/1 or /jobs/1.json
      def show
         @job = Job.find(params[:id])
         @company = @job.company
      end
    

    This might throw some errors since you have optional: true in your relation. Also, I didn't care of n+1 queries since it's just a record, but this could be improved to be only 1 SQL query to the database.