Skip to content

Instantly share code, notes, and snippets.

@namtx
Last active May 24, 2017 08:45
Show Gist options
  • Save namtx/0976879946b564174d1c2a4e9acae7e4 to your computer and use it in GitHub Desktop.
Save namtx/0976879946b564174d1c2a4e9acae7e4 to your computer and use it in GitHub Desktop.

problems

class Address < ActiveRecord::Base
  belongs_to :customer
end

class Customer <ActiveRecord::Base
  has_one :address
  has_many :invoices
end

class Invoice < ActiveRecord::Base
  belongs_to :customer
end
<%= @invoice.customer.name %>
<%= @invoice.customer.address.city %>
<%= @invoice.customer.address.street %>
<%= @invoice.customer.address.state %>

solutions

  1. use only one dot
class Address < ActiveRecord::Base
  belongs_to :customer
end

class Customer < ActiveRecord::Base
  has_one :address
  has_many :invoices
  
  def street
    address.street
  end
  
  def city
    address.city
  end
end

class Invoice < ActiveRecord::Base
  belongs_to :customer
  
  def customer_name
    customer.name
  end
  
  def customer_street
    customer.street
  end
  
  def customer_city
    customer.city
  end
end
  <%= @invoice.customer_name %>
  <%= @invoice.customer_city %>
  <%= @invoice.customer_street %>

tooo many methods

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment