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

后端 未结 5 427
南旧
南旧 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:21

    For creating new instances you could use factories. For this you could simply use FactoryGirl https://github.com/thoughtbot/factory_girl

    So after you have defined your factory soewhat like this:

    FactoryGirl.define do factory :job do client FactoryGirl.create(:client) subject 'Test' description 'This is a Test'

    You could then call FactoryGirl.create(:job) to generate a new job like that. You could also call FactoryGirl.build(:job, client: aClientYouInstantiatedBefore, subject: 'AnotherTest') and also overwrite any other attributes

    Factores are good if you want to create many objects, that are similar in a certain way.

提交回复
热议问题