Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 580
user2158382 Avatar asked Apr 29 '13 19:04

user2158382


4 Answers

Just call create on the jobs collection of the client:

c = Client.find(1)
c.jobs.create(:subject => "Test", :description => "This is a test")
like image 133
alf Avatar answered Nov 01 '22 00:11

alf


You can pass the object as argument to create the job:

client = Client.create
job = Job.create(client_id: client.id, subject: 'Test', description: 'blabla')

The create method will raise an error if the object is not valid to save (if you set validations like mandatory name, etc).

like image 22
MrYoshiji Avatar answered Oct 31 '22 23:10

MrYoshiji


You can use create_job in this way:

client = Client.create
job = client.create_job!(subject: 'Test', description: 'blabla')

When you declare a belongs_to association, the declaring class automatically gains five methods related to the association:

association
association=(associate)
build_association(attributes = {})
create_association(attributes = {})
create_association!(attributes = {})

In all of these methods, association is replaced with the symbol passed as the first argument to belongs_to.

more: http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference

like image 4
Meysam Salehi Avatar answered Oct 31 '22 22:10

Meysam Salehi


Pass the object itself as an argument, instead of passing its ID. That is, instead of passing :client_id => 1 or :client_id => client.id, pass :client => client.

client = Client.find(1)
Job.create(:client => client, :subject => "Test", :description => "This is a test")
like image 3
Rory O'Kane Avatar answered Oct 31 '22 22:10

Rory O'Kane