0

I have following models in a Rails application.

class Address < ActiveRecord::Base
  belongs_to :addressable, :polymorphic => true
end

class Client < ActiveRecord::Base
  has_one :address, :as => :addressable, dependent: :destroy
  accepts_nested_attributes_for :address, :allow_destroy => true

  has_many :invoices
end

class Invoice < ActiveRecord::Base
  belongs_to :client
end

While I am able to retrieve the client name using

@invoice.client.name 

I am not able to retrieve the address information in the similar manner.

How do I retrieve the address attributes in the view for invoice?

4

1 回答 1

0

@ invoice.client.address 就是答案。但我建议您使用方法委托遵循得墨忒耳法则

http://en.wikipedia.org/wiki/Law_of_Demeter
http://api.rubyonrails.org/classes/Module.html#method-i-delegate

基本上这个想法是你可以这样做:@invoice.client.address_street o 更好的@invoice.client_address_street

于 2013-10-18T20:12:21.477 回答