2013-04-29 97 views
9

我正在尝试在具有belongs_to关系的模型的数据库中添加一个新条目。我有2个模型,工作和客户。Ruby on Rails:使用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 
+0

'client = Client.new; (): Job.create(:client => client,:subject =>“Test”,:description =>“这是一个测试”) – tessi 2013-04-29 19:47:18

回答

12

就叫createjobs收集客户端:

c = Client.find(1) 
c.jobs.create(:subject => "Test", :description => "This is a test") 
+1

不好,如果没有id = 1的条目,会引发ActiveRecord :: RecordNotFound ....使用Client.find(:first)或Client.first – MrYoshiji 2013-04-29 19:50:33

+3

@MrYoshiji引发异常通常是预期的行为因为在rails中,RecordNotFound异常在异常应用程序中被转换为404请求。 – alf 2013-04-29 19:51:55

+0

谢谢我似乎最喜欢这个解决方案。 – user2158382 2013-04-29 20:06:39

-3

要创建新的实例,您可以使用工厂。为此,你可以简单地使用FactoryGirl https://github.com/thoughtbot/factory_girl

您已经定义了工厂soewhat这样所以经过:

FactoryGirl.define做 厂:工作做 客户FactoryGirl.create(:客户端) 主题“测试” description'This is a Test'

然后,您可以调用FactoryGirl.create(:job)来生成一个新的工作。 你也可以拨打FactoryGirl.build(:作业时,客户端:aClientYouInstantiatedBefore,主题:“AnotherTest”),并覆盖任何其他属性

,如果你想创建了很多对象,是在以某种方式相似Factores都不错。

+1

在他的问题中没有任何地方提到他希望按照规格来做。 – kiddorails 2013-04-29 19:50:06

+0

你可以在任何地方使用工厂,不仅在规格或测试 – MentholBonbon 2013-04-29 20:01:46

+6

如果你使用工厂女孩的发展,你做错了。 – Senjai 2014-05-30 18:21:59

1

您可以传递对象作为参数来创建工作:

client = Client.create 
job = Job.create(client_id: client.id, subject: 'Test', description: 'blabla') 

create方法会提高,如果一个错误对象无效保存(如果您设置验证如强制名称等)。

+0

这只适用于'client'被标记为'attribute_accessible' – alf 2013-04-29 19:53:22

+0

固定,谢谢你的评论@alfonso – MrYoshiji 2013-04-29 19:54:24

+0

这也可以,但我更喜欢其他语法。 – user2158382 2013-04-29 20:07:16

1

将对象本身作为参数传递,而不是传递其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") 
0

可以以这种方式使用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