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

后端 未结 5 432
南旧
南旧 2021-01-11 12:04

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

5条回答
  •  不要未来只要你来
    2021-01-11 12:32

    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")
    

提交回复
热议问题