【问题标题】:Rails: polymorphic associationsRails:多态关联
【发布时间】:2015-10-17 23:01:39
【问题描述】:

我正在使用 Rails 4 构建应用程序。

我有一个地址模型和一个电话模型。它们中的每一个都被定义为具有许多其他模型的多态,因此它们可以在整个应用程序中使用——例如,用户有电话号码,但公司也有。他们的数字可能不同。公司有一个地址,用户可以将其用作默认地址,也可以添加另一个地址作为自己的地址。

在我的代码中,我有一个地址模型:

class Address < ActiveRecord::Base

  geocoded_by :full_address_map   # can also be an IP address


  # --------------- associations

  belongs_to :addressable, :polymorphic => true

  # --------------- scopes

  # --------------- validations

  validates_presence_of :unit, :street, :zip, :country 


  # --------------- class methods

  def first_line
    [unit, street].join(' ')
  end

  def middle_line
    if self.building.present? 
    end
  end

  def last_line
    [city, region, zip].join('   ')
  end

  def country_name
    self.country = ISO3166::Country[country]
    country.translations[I18n.locale.to_s] || country.name
  end

  def address_without_country
    [self.first_line, middle_line, last_line].compact.join(" ")
  end

  def full_address_map
    [self.first_line, middle_line, last_line, country_name.upcase].compact.join("<br>").html_safe
  end

  def full_address_formal
    [self.first_line, middle_line, last_line, country_name].compact.join(" ").html_safe
  end


  # --------------- callbacks

  after_validation :geocode#, if  self.full_address.changed? 

  # --------------- instance methods

  # --------------- private methods

  protected

end

在我的地址_form partial,我有表格供用户填写。

在我的组织模型中,我有:

class Organisation < ActiveRecord::Base

  # --------------- associations

    has_one :user # the user that is the representative 
    has_many :profiles # the users who have roles within the org


    has_many :addresses, :as_addressable
    has_many :phones, :as_phoneable


  # --------------- scopes



  # --------------- validations

  # --------------- class methods


  def address
    self.address.full_address_formal
  end


  # --------------- callbacks

  # --------------- instance methods

  # --------------- private methods


end

在我的组织控制器中,新操作,我有:

def new
    @organisation = Organisation.new
    @organisation.build_address
end

当我尝试这个时,我有这个错误:

NoMethodError at /organisations/new
undefined method `arity' for :as_addressable:Symbol

在我的地址表中,我有:

t.integer  "addressable_id"
t.string   "addressable_type"
add_index "addresses", ["addressable_type", "addressable_id"], name: "index_addresses_on_addressable_type_and_addressable_id", unique: true, using: :btree

我不明白错误的性质。这个结构缺少什么?

【问题讨论】:

    标签: ruby-on-rails polymorphic-associations


    【解决方案1】:

    多态关联需要在其声明中使用as 选项。

    has_many :addresses, as: :addressable
    has_many :phones, as: :phoneable
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      • 2019-03-14
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多