PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, May 18, 2022

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

 May 18, 2022     methods, model, partial, ruby, ruby-on-rails     No comments   

Issue

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


Answered By - SteveTurczyn
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing