ActiveRecord:如何引用同一个类

时间:2016-10-03 14:26:05

标签: ruby activerecord

我有一个表格,primary_address_iddelivery_address_id列引用包含街道地址的表格中的行。我想用ActiveRecord创建模型,所以我可以写

ci = Contact.create(full_name: 'Willy', company: 'Chocolate Factory')
pa = ci.primary_address.create(street: 'Seestrasse', city: 'Kilchberg')
da = ci.delivery_address.create(street: 'Flughafenstrasse', city: 'Zurich')

(基本上我希望实现类似于an example on RoR guides的功能。)

contact.rb:
class Contact < ActiveRecord::Base
  belongs_to :primary_address, :class_name => 'Address'
  belongs_to :delivery_address, :class_name => 'Address'
end
address.rb:
class Address < ActiveRecord::Base
end

当我尝试从上面的示例中运行ci.primary_address.create时,我得到:

...activemodel-5.0.0.1/lib/active_model/attribute_methods.rb:433:in `method_missing': undefined method `create' for #<Address:0x007f8ef9132128> (NoMethodError)
    from /.../main.rb:16:in `<top (required)>'
    from -e:1:in `load'
    from -e:1:in `<main>'

我想知道我的模型是否有任何意义以及为什么创建方法不可用?

我在Rails之外使用ActiveRecord。

CREATE TABLE contacts
(
    id INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
    name VARCHAR(20),
    company VARCHAR(20),
    primary_address_id INT(11),
    delivery_address_id INT(11),
    CONSTRAINT primary_address_fk FOREIGN KEY (primary_address_id) REFERENCES addresses (id) ON DELETE SET NULL,
    CONSTRAINT delivery_address_fk FOREIGN KEY (delivery_address_id) REFERENCES addresses (id) ON DELETE SET NULL
);
CREATE TABLE addresses
(
    id INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
    street VARCHAR(40),
    city VARCHAR(20),
);

1 个答案:

答案 0 :(得分:0)

您会注意到,在您引用的示例中,两个模型之间的关系是另一种方式。您的联系人记录属于您的地址记录,而在示例中,该关系是has_many。

has_many(或其好友has_one)可能是一种在这里表达关系的更自然的方式 - 除非您打算将一个地址记录附加到许多联系人记录中。

刚检查了rails文档 - has_many为您提供了create()方法; belongs_to没有。

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html