Dennis Stevenson
Dennis Stevenson

Reputation: 61

linking rails objects through foreign keys

What is the best way to link rails objects through foreign keys? Here is my example. a Practitioner has a timecard (collect hours worked per day). I want to put the practitioner's id on the appointment to show this:

from routes.rb

  resources :locations do
    resources :practitioners, only: [:new, :create]
  end

  resources :practitioners, except: [:new, :create] do
    resources :timecards, except: :delete
    resources :appointments
  end

timecard.rb - you can see here I forced the timecard.practitioner_id to be 3, but that was a brute force testing effort.

class Timecard < ActiveRecord::Base
  belongs_to :practitioner
 attr_protected :id

  before_save :set_practitioner_id

  def set_practitioner_id
    if self.practitioner_id.blank?
      self.practitioner_id = 3
    end
  end
end

And from my controller...

def create
    @practitioner = Practitioner.find(params[:practitioner_id])
    @timecard = Timecard.create(params[:timecard])


    respond_to do |format|
      if @timecard.save
        format.html { redirect_to @practitioner, notice: 'Timecard was successfully created.' }
        format.json { render json: @timecard, status: :created, location: @timecard }
      else
        format.html { render action: "new" }
        format.json { render json: @timecard.errors, status: :unprocessable_entity }
      end
    end
  end

I can see the parameter for the practitioner_id = 3 (which is what I want to use), I just don't know how to access it in the code.

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"DIp4R31McXnBNP4NB06KDTzV+8lLcWvxbq1w9J+Z1+M=",
 "timecard"=>{
   "hours_worked"=>"2",
   "activity_date(1i)"=>"2013",
   "activity_date(2i)"=>"3",
   "activity_date(3i)"=>"20",
   "practitioner_id"=>"",
   "location_id"=>"1"
 },
 "commit"=>"Create Timecard",
 "practitioner_id"=>"3"   <== this is what I want to use
}

Upvotes: 1

Views: 165

Answers (2)

jvnill
jvnill

Reputation: 29599

I'm assuming that a practitioner has many timecards so you should be able to do something like

# practitioner.rb
has_many :timecards

# controller
@practitioner = Practitioner.find(params[:practitioner_id])
@timecard = @practitioner.timecards.build(params[:timecard])

having the association set up will take care of setting the foreign keys for you.

Upvotes: 0

Dan Wich
Dan Wich

Reputation: 4943

If I understand your question, you can simply set @timecard.practitioner = @practitioner before saving your timecard in the controller. You can do that because belongs_to gives you a practioner= method that "Assigns the associate object, extracts the primary key, and sets it as the foreign key."

Upvotes: 1

Related Questions