Search code examples
ruby-on-railshas-one

Finding corresponding has_one row in rails


If a job has_one cv associated with it:

class Job < ActiveRecord::Base
    has_one :cv
end

I've set the routes up as follows:

  resources :jobs do
    resource :cv
  end

When I want to create a CV for a job I following the following link:

  <%= link_to "Add CV", new_job_cvs_path(j) %>

Which is associated with the following method in the CV controller:

  def new
    @job = Job.find(params[:job_id])
    @job_cv = @job.cv.new
  end

However this results in me getting the following error, for the @job_cv line:

SQLite3::SQLException: no such column: cvs.job_id: SELECT "cvs".* FROM "cvs" WHERE "cvs"."job_id" = ? LIMIT 1

I think I've set something up wrong somewhere, I just don't know where yet...


Solution

  • You forgot to create a migration for your new relationship, create new migration by

    rails g migration AddCvToJobs
    

    Then edit the newly created migration file in app/db/migrate/xxx_add_cv_to_jobs.rb:

    class AddCvToJobs < ActiveRecord::Migration
      def change
        add_column :cvs, :job_id, :integer, index: true
      end
    end
    

    Then run rake db:migrate and try again.