Search code examples
ruby-on-railshas-manybelongs-to

Force create a record with a belongs_to association


I have 2 models. Job and User. User has_many :jobs and Job belongs_to :user

Is it at all possible for me to create a Job record with Job.create(location: "test") without defining a User? If I try this currently I am getting a Couldn't find User with 'id'= error. I assume this is because of the associations.

Any way I can do this without a User ID? I want to add the user_id only later.

Thanks!


Solution

  • To be clear, yes this is possible.

    Associations in your models are only there to set foreign keys in your datatables. As such, if you wanted to create a Job (although it belongs_to :user), you'd be able to set all the attributes you desired, and then update :user_id later.

    Here's a good reference:

    enter image description here

    This shows the datatable structure for the typical belongs_to / has_many association. Whilst to associate the two objects, you need to have the correct foreign_key, you can populate them as you wish.