如何从部分执行的模型中获取方法?

How do I get a method from my model executed in a partial?

我正在使用 Rails 4.2.7。我有一部分

<%= @my_object_time.my_object.address.formatted %>

我在 app/models/address.rb 中定义了这个方法…

class Address < ActiveRecord::Base
  belongs_to :state
  belongs_to :country
  has_one :user  # , dependent: :destroy
  has_one :race

  def self.formatted
    str = ""
    if self.city && !self.city.empty?
      str = "#{city}"
    end
    if self.state
      str = str.empty? ? "#{state.iso}" : "#{str}, #{state.iso}"
    end
    if self.country
      str = str.empty? ? "#{country.name}" : "#{str}, #{country.name}"
    end
    str
  end

但是,当我调用部分时,出现此错误

ActionView::Template::Error (undefined method `formatted' for #<Address:0x007fb062e31fb0>):

如何更正上述错误以执行我的方法的逻辑?我也试过只“格式化”而不是“self.formatted”但是得到了同样的错误。

您已将 formatted 定义为 class 方法...

  def self.formatted
    str = ""
    if self.city && !self.city.empty?
      str = "#{city}"
    end
    if self.state
      str = str.empty? ? "#{state.iso}" : "#{str}, #{state.iso}"
    end
    if self.country
      str = str.empty? ? "#{country.name}" : "#{str}, #{country.name}"
    end
    str
  end

你要的是实例方法。另外,您不需要所有这些 self 前缀。

  def formatted
    str = ""
    if city && !city.empty?
      str = "#{city}"
    end
    if state
      str = str.empty? ? "#{state.iso}" : "#{str}, #{state.iso}"
    end
    if country
      str = str.empty? ? "#{country.name}" : "#{str}, #{country.name}"
    end
    str
  end