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

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

    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

    0 讨论(0)
  • 2021-01-11 12:20

    Just call create on the jobs collection of the client:

    c = Client.find(1)
    c.jobs.create(:subject => "Test", :description => "This is a test")
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-11 12:28

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

    0 讨论(0)
  • 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")
    
    0 讨论(0)
提交回复
热议问题