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

时间:2016-10-10 16:07:48

标签: ruby-on-rails ruby methods model 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

但是,当我调用partial时,我收到此错误

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

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

1 个答案:

答案 0 :(得分:1)

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

  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