Rails: find_by_sql and virtual column

前端 未结 2 565
有刺的猬
有刺的猬 2020-12-29 09:51

I want to display a list with tags plus the number of elements (in my example \"Tasks\") for each tag.

For this purpose I created the following method in my Tag mode

2条回答
  •  梦毁少年i
    2020-12-29 10:07

    The count is there, you just can't see it since taskcount is not an attribute Rails creates for that class Task, because it isn't a column that it can see. You have to use the attributes call to find it. Sample:

    class Tag < ActiveRecord::Base
      ...
      def taskcount
        attributes['taskcount']
      end
    end
    
    Tag.find_with_count.each do |t|
      puts "#{t.name}: #{t.taskcount}"
    end
    

提交回复
热议问题