Rails ActiveRecord在记录结果中插入计数字段

Rails ActiveRecord在记录结果中插入计数字段,activerecord,model,Activerecord,Model,大家好,谢谢你们的帮助: class User < ActiveRecord::Base attr_accessible :label, :description, :number has_many :user_posts has_many :posts, through: :user_posts after_initialize :count protected def count self.number = posts.count end en

大家好,谢谢你们的帮助:

class User < ActiveRecord::Base
  attr_accessible :label, :description, :number

  has_many :user_posts
  has_many :posts, through: :user_posts

  after_initialize :count

  protected
  def count
    self.number = posts.count
  end
end
class用户
我希望:number字段是用户所有帖子的计数(我认为必须在我在模型中创建的函数count中定义)。注意:number字段不仅在模型中的DB中,而且我希望它在用户返回的记录中可用。最后一个示例

我对ActiveRecord非常陌生,所以也许我不需要这样做,我愿意接受任何建议。

试试这个:

class User < ActiveRecord::Base
  attr_accessible :label, :description
  attr_accessor :number

  has_many :user_posts
  has_many :posts, through: :user_posts

  after_initialize :count

  protected
  def count
    self.number = posts.count
  end

end
class用户
您不需要在
attr\u accessible
列表中指定
:number
,因为您没有从uer获取
number
的值,对吗


对于仅模型属性(非持久性),最简单的方法是使用
attr\u访问器

,谢谢你的回答。代码可以工作。但我认为我在我想要的方面做错了。我需要在json数组中呈现我的结果,在每个json(每个用户)中,我需要插入一个字段(数字)witch是用户的帖子总数。我认为在模型中这样做是件好事,但我无法在ActiveRecord结果中访问它。我怎么做?你应该检查
rabl
gem。还有一个railscast。伙计,这正是我需要的。只需在我的rabl集合中添加一个节点,它就可以工作了;p
node(:number){| user | user.posts.count}