Search code examples
ruby-on-railsstring-concatenation

In Rails how can I prefix id with letter "N" and save as item number


I need to be able to create an item number based on the product id, prefixed by the letter "N". I have seen these two questions about prefixing and using callbacks.

I am new to Ruby on Rails and programming in general. How can I combine both questions so that after_save my item number field will be updated with the newly concatenated K + id?

I am using Ruby 2.3 and Rails 4.2.5.

Update - Final Solution Thanks to @born4new, the final code I used in my model to get this to work is as follows.

class Product < ActiveRecord::Base
  after_save :create_item_number

  private
    # Concatenate ID with prefix N to create item number
    def create_item_number
      update_column(:item_number, self.item_number = "N#{id}")
    end
end

Solution

  • You can do a simple string concatenation like so:

    after_save :prefix_number
    
    [...]
    
    private
    
    def prefix_number
      self.number = "N#{id}"
    end