bdunagan

fill the void - bdunagan

26 Sep 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
Previous LinkedIn Twitter GitHub Email Next