mardi 28 novembre 2017

Add attribute to Rails 5 model, which not exists in the database

I have tables - users and articles. It is one to many relation or user can have many articles. What I want is to select all users from users table with LIMIT 40, but include count all articles for each user - add property for each user count_articles. I am trying in this way:

def self.get_users(limit, offset)
  users = []
  order('created_at').limit(limit).offset(offset).each do |user|
    user.attributes[:count_articles] = user.articles.count
    users << user
    byebug
  end
  users
end

, but I am getting users without this attribute. If I use byebug and type in the console - user.count_articles, I can see the result of count_articles for current user, but if I type only user, I see all the attributes without count_articles.

Aucun commentaire:

Enregistrer un commentaire