I would like to get the object obtained by ActiveRecord with hash including the attributes that are not in the DB column.

Asked 2 years ago, Updated 2 years ago, 34 views

CREATE TABLE users(
  id INT NOT NULL AUTO_INCREMENTEN
  name VARCHAR(32),
);
class User<ActiveRecord::Base
  attr_accessor:hoge

  default_hoge
    self.hoge="hogehoge"
  end
end

On the rails command line

>user=User.take
>user.set_hoge
>user.attributes


{"id"=>1, "name"=>"Tom"}, but

{"id"=>1, "name"=>"Tom", "hoge"=>"hogehoge"}
I would like to know how to return it like this!
I look forward to your kind cooperation.

ruby-on-rails ruby

2022-09-29 22:49

1 Answers

You can use the as_json method to return the results of the instance method.

>user=User.take
>user.set_hoge
>user.as_json(methods::hoge)# or user.as_json(methods:[:hoge])


2022-09-29 22:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.