Search code examples
ruby-on-railsrubymethodsmodelpartial

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


I’m using Rails 4.2.7. I have this in a partial

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

I have this method defined in my 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

However, when I invoke the partial, I get this error

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

How do I correct the above error in order to get the logic of my method executed? I also tried just “formatted” instead of “self.formatted” but got the same error.


Solution

  • You have formatted defined as a class method...

      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
    

    What you want is an instance method. Plus you don't need all those self prefixes.

      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