rails,一起编辑的资源的多个实例,RESTful方式

时间:2014-11-13 17:30:43

标签: ruby-on-rails rest

在我的应用程序中,我有一个名为Customer的RESTful资源。
但是每个客户都有一组以固定方式限制的资源,即:shipping_address,company_address,warehouse_address。
从数据库或REST角度来看,资源是地址,在数据库级别,我有一个地址,其中包含一个名为type的字段,其中包含' shipping',' company',' ;仓库'其中的价值观。
但它们表示在同一个网页上,类似于公司/ id /地址。
我如何管理这个但是试图强制执行rails的RESTful方向?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,这将有效:

# models/customer.rb
class Customer < ...
  belongs_to :shipping_address, class_name: 'Address'
  belongs_to :company_address, class_name: 'Address'
  belongs_to :warehouse_address, class_name: 'Address'
end

# models/address.rb
class Address < ...
  has_many :shipping_customers, foreign_key: 'shipping_address_id', class_name: 'Customer'
  has_many :company_customers, foreign_key: 'company_address_id', class_name: 'Customer'
  has_many :warehouse_customers, foreign_key: 'warehouse_address_id', class_name: 'Customer'
end

以下是在rails控制台上运行的已编辑示例,用于对其进行设置并在现有应用中进行验证:

$ rails g model Customer name:string shipping_address_id:integer company_address_id:integer 
$ rails g model Address details:string address_type:string
$ bin/rake db:migrate
$ rails c
...(Rails 4.1.5)
irb(main):001:0> @company_address = Address.create! details: 'company address', address_type: 'company'
=> #<Address id: 1, details: "company address", address_type: "company">
irb(main):002:0> @shipping_address = Address.create! details: 'shipping address', address_type: 'shipping'
=> #<Address id: 2, details: "shipping address", address_type: "shipping">
irb(main):003:0> Customer.create! name: 'some customer', shipping_address: @shipping_address, company_address: @company_address
=> #<Customer id: 1, name: "some customer", shipping_address_id: 2, company_address_id: 1>
irb(main):004:0> Customer.first.shipping_address
=> #<Address id: 2, details: "shipping address", address_type: "shipping">
irb(main):005:0> Customer.first.company_address
=> #<Address id: 1, details: "company address", address_type: "company">

如果有必要,您可以在将地址用于特定客户之前验证地址是否具有正确的address_type。