Ruby on rails: Creating a model entry with a belongs_to association

user2158382 picture user2158382 · Apr 29, 2013 · Viewed 27k times · Source

I am trying to add a new entry in my database for a model that has a belongs_to relationship. I have 2 models, Jobs and Clients.

It was easy enough to find tutorial on how to set up the association between these two (using has_many and belongs_to), but I can't seem to find any examples where the association is actually used.

In my code, I am trying to create a new job for the first client. The jobs model has an attribute for client_id, and I know I can probably just manually fill the attribute, but there has to be some ruby convention to easily accomplish this.

Job.create(:client_id => 1, :subject => "Test", :description => "This is a test")

I can easily put that in my code, but I feel like ruby has a better way to do this. Here is the way my models are setup

class Job < ActiveRecord::Base
  attr_accessible :actual_time, :assigned_at, :client_id, :completed_at, :estimated_time, :location, :responded_at, :runner_id, :status, :subject, :description
  belongs_to :client
end

class Client < User
    has_many :jobs
end

class User < ActiveRecord::Base
  attr_accessible :name, :cell, :email, :pref

end

Answer

alf picture alf · Apr 29, 2013

Just call create on the jobs collection of the client:

c = Client.find(1)
c.jobs.create(:subject => "Test", :description => "This is a test")