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

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


Just call create on the jobs collection of the client:

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


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

client = Client.createjob = 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).


You can use create_job in this way:

client = Client.createjob = 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:

associationassociation=(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