bdunagan

bdunagan

September 26 2020
Rails Tip: Non-Database Attribute in ActiveRecord SQL Query

ActiveRecord in Rails makes it easy to collect items using SQL commands, but if you want to also add attributes that are not database columns, this is what to do:

class TestObject < ActiveRecord::Base
  def test_attribute
    return true
  end
  def items
    # This will return your query with "test_attribute" and its value inserted into every row.
    Item.where("your sql query").select("#{self.test_attribute} as test_attribute")
  end
end
Rails Tip: How to Insert Middleware First Retrospect Engineering Internship Program 2020
LinkedIn GitHub Email