Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails make model methods appear as attributes

I have a model connecting to a Postgres db.

class Person < ApplicationRecord

  def say_id
    "#{name} has id: #{id}"
  end

end

I have some attributes id,name,email as well as the method above: say_id that can be accessed via:

person = Person.new
person.id => 1
person.say_id  => "John has id: 1"

I would like to have the method 'say_id' listed as an attribute as well, now when running person.attributes, I'm only seeing: id, name, email

How can I have my method included as a listable information in full, as with person.attributes but which will include my method? A usecase would be for lazily just laying out all these fields in a table of the Person-object.

like image 983
JUlinder Avatar asked Feb 24 '26 03:02

JUlinder


1 Answers

In Rails 5+ you can use the attributes api to create attributes that are not backed by a database column:

class Person < ApplicationRecord
  attribute :foo
end
irb(main):002:0> Person.new.attributes
=> {"id"=>nil, "email"=>nil, "name"=>nil, "created_at"=>nil, "updated_at"=>nil, "foo"=>nil}

Unlike if you used attr_accessor these actually behave very much like database backed attributes.

You can then override the getter method if you wanted to:

class Person < ApplicationRecord
  attribute :foo

  def foo
    "foo is #{super}"
  end
end
irb(main):005:0> Person.new(foo: 'bar').foo
=> "foo is bar"

But for whatever you're doing its still not the right answer. You can get a list of the methods of an class by calling .instance_methods on a class:

irb(main):007:0> Person.instance_methods(false)
=> [:foo]

Passing false filters out inherited methods.

like image 186
max Avatar answered Feb 26 '26 15:02

max



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!