在rails 3.2.8中,如何使用其中一个变量创建另一个模型?

时间:2013-07-19 16:22:21

标签: ruby-on-rails ruby ruby-on-rails-3

我有2个模型,StateOffice

Office has_one State
Office name: string, city: string, state: State

State belongs_to Office 
State name: string, Abbrv: string

我是红宝石的新手,所以我正在弄清楚它是如何工作的。我想创建一个Office将是:

Office.create( name: 'The Building', city: 'Kansas', state: State.first )

当我看到保存的内容时,我得到state: nil

我做错了什么?

2 个答案:

答案 0 :(得分:0)

您的数据库表似乎使用:state而不是:state_id。 Office应该在数据库中有一个名为:state_id的列。

当您在Office上调用save时,它将保存状态的ID。当您调用office.state时,它将自动从数据库中获取状态。当您致电office.save时,如果尚未保留到数据库,它还会保存附加的state

答案 1 :(得分:0)

澄清......您在模型和表之间的关系之间创建关联。 要创建一对一关联,请分别设置has_one :name_of_the_child_modelbelongs_to :name_of_the_parent_model。在你的例子中:

班级办公室< ActiveRecord :: Base
attr_accessible:name,:city
has_one:州

类状态< ActiveRecord :: Base
attr_accessible:name,:abbrv
belongs_to:办公室 端

之后,您可以在相应的表之间创建关系。您可以通过将父表(Office模型)的主键设置为子表(状态模型)中的新字段/列来实现,因此状态模型如下所示:

类状态< ActiveRecord :: Base
attr_accessible:name,:abbrv,:office_id
belongs_to:办公室 端

要一步在Office对象上实例化并保存新的State对象,可以使用.create_modelname(attributes={})方法:
office = Office.find(id)
office.create_state({name: "state_name", abbr: "abbrv"})

你得到nil,因为State.first只是试图从你之前写过的状态表中读取第一个对象。