2

I am creating an application that tracks customers with quotes. Customer has many quotes and one belongs to one customer. I am trying to use a method that combines a first name and last name fields to produce a full name. My code is as follows.

Customer Model:

class Customer < ActiveRecord::Base
  has_many :quotes
  def full_name
    "#{FName} #{LName}"
  end
end

Quotes form.html.erb

<div class="field">
  <%= f.label :Customer_Name %><br>
  <%= collection_select :Quote, :Customer_id, Customer.all, :id, :full_name, {}, {:multiple => true} %>
  </div>

When I try to create a new record, I am given an "uninitialized constant Customer::FName" error. Could someone please advise?

2
  • 1
    In rails anything that start with Uppercase or in Uppercase considered to be constant, FName and LName is referred as constants and constants should be defined before use Commented Apr 25, 2015 at 19:10
  • Thank you Pramod. This was my issue, thanks for the help! Commented Apr 25, 2015 at 19:40

1 Answer 1

1

In Ruby anything identifier which begins with an uppercase letter is a constant.

irb(main):001:0> FOO = 'bar'
=> "bar"
irb(main):002:0> FOO = 'baz'
(irb):2: warning: already initialized constant FOO
(irb):1: warning: previous definition of FOO was here
=> "baz"
irb(main):003:0> 

So class names which are constants are written in camelcase (GhostWriter) and attributes and methods are commonly written in snake_case.

Actual constants are written with all uppercase.

So to bring it all together

class Square # the class name Square is a constant
  SIDES = 4 # a constant

  attr_accessor :height 
  attr_accessor :width
  attr_accessor :background_color # attributes are written in snakecase

  def area 
    @height * width
  end

  def get_point # so are method names.
  end 
end
Sign up to request clarification or add additional context in comments.

3 Comments

The issue was that I named my attributes with capitalization, which made them constants. Thank you for your help and prompt response. I sincerely appreciate it!
There is nothing forcing you to write method names in snake case - Ruby only cares what the case of the first letter is and won't complain if you call it firstName or fIrStNaMe. However other programmers will since this is the accepted style.
There isn't even anything stopping you from writing methods in ALLCAPS or with the first letter capitalized. See Kernel#Float as a single sample of many similar methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.