Ruby on rails:使用belongs_to关联创建模型条目
我正在尝试在我的数据库中为具有belongs_to关系的模型添加新条目。 我有两个模型,乔布斯和客户。
很容易找到关于如何在这两者之间建立关联的教程(使用has_many和belongs_to),但我似乎无法找到实际使用关联的任何示例。
在我的代码中,我正在尝试为第一个客户创建一个新工作。 作业模型有一个client_id的属性,我知道我可能只是手动填充属性,但必须有一些ruby约定来轻松实现这一点。
Job.create(:client_id => 1, :subject => "Test", :description => "This is a test")
我可以很容易地将它放在我的代码中,但我觉得ruby有更好的方法来做到这一点。 这是我的模型设置方式
class Job < ActiveRecord::Base attr_accessible :actual_time, :assigned_at, :client_id, :completed_at, :estimated_time, :location, :responded_at, :runner_id, :status, :subject, :description belongs_to :client end class Client < User has_many :jobs end class User < ActiveRecord::Base attr_accessible :name, :cell, :email, :pref end
只需在客户端的jobs
集合上调用create
:
c = Client.find(1) c.jobs.create(:subject => "Test", :description => "This is a test")
您可以将对象作为参数传递以创建作业:
client = Client.create job = Job.create(client_id: client.id, subject: 'Test', description: 'blabla')
如果对象无效保存(如果设置强制名称等validation),则create
方法将引发错误。
将对象本身作为参数传递,而不是传递其ID。 也就是说,不是传递:client_id => 1
或:client_id => client.id
,传递:client => client
。
client = Client.find(1) Job.create(:client => client, :subject => "Test", :description => "This is a test")
您可以这样使用create_job
:
client = Client.create job = client.create_job!(subject: 'Test', description: 'blabla')
声明belongs_to
关联时,声明类会自动获得与关联相关的五种方法:
association association=(associate) build_association(attributes = {}) create_association(attributes = {}) create_association!(attributes = {})
在所有这些方法中,关联被替换为作为belongs_to
的第一个参数传递的符号。
更多: http : //guides.rubyonrails.org/association_basics.html#belongs-to-association-reference
要创建新实例,您可以使用工厂。 为此你可以简单地使用FactoryGirl https://github.com/thoughtbot/factory_girl
所以,在你定义了你的工厂之后,就像这样:
FactoryGirl.define do factory:job do client FactoryGirl.create(:client)subject’Test’描述’这是一个测试’
然后,您可以调用FactoryGirl.create(:job)来生成这样的新作业。 你也可以调用FactoryGirl.build(:job,client:aClientYouInstantiatedBefore,subject:’AnotherTest’)并覆盖任何其他属性
如果你想创建许多以某种方式相似的对象,Factores是很好的。