2015-10-26 66 views
1

我已经画了自己的角落。重构属性到模型关联

我有被定义的模型:

create_table "invoices", force: :cascade do |t| 
    t.string "organization" 
    ... 
end 

现在的业务规则已经改变,我需要一个“组织”对象在其位置被链接。

我已经有一个组织模型。我可以轻松地将'organization_id'属性添加到Invoice模型并声明关联。

模型更新后,恐怕我不能再获取'组织'的字符串值,因为'组织'属性将被关联魔术方法掩盖?

那么,如何定义一个迁移步骤来将当前发票表更新为find_or_create_by(name:xxx>),其中xxx是组织列中的当前字符串?

回答

1

你总是可以使用:read_attribute方法为您的发票模型。如果你想获得属性值:

@invoice.read_attribute(:organization) 
1

organization_id是,你会从Organization模型调用关联的数据,所以,我会得到name /其他数据的整点从如果是我:

#app/models/invoice.rb 
class Invoice < ActiveRecord::Base 
    belongs_to :organization 
    alias_attribute :name, :location, to: :organization, prefix: true #-> organization_name 
end 

这将允许你以包括invoicesorganization_id,对此你就能够调用关联的数据像这样:

@invoice = Invoice.find params[:id] 
@invoice.organization_name #-> "Name" 

如果你想要一台组织在invoices领域,你必须重新命名的关联关系:

#app/models/invoice.rb 
class Invoice < ActiveRecord::Base 
    belongs_to :partner, class_name: "Organization", foreign_key: :organization_id 
end 
+0

你的意见给了我一些有价值的未来想法。 –

+0

感谢彼得 - 希望它有所帮助 –