2013-08-20 46 views
0

嗨计数领域的所有感谢您的帮助:Rails的ActiveRecord的插入记录结果

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 

我whant领域:编号是(我认为必须在定义用户的所有帖子的计数函数计数我在模型中创建的。注意:数字字段不在数据库中,只在模型中,但我希望它在User.last返回的记录中可用,例如

我真的很新以ActiveRecord,所以也许它不是这种方式我需要去,我可以任何消化。

回答

0

试试这个:

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 

你不需要在attr_accessible列表指定:number你不是从UER正确服用number价值?

对于模型只属性(不执着),最简单的方法是,使用attr_accessor

+0

谢谢回答。代码起作用。但我认为我做错了我想要的东西。我需要将我的结果呈现在json数组中,并且在每个json(每个用户)中,我需要插入一个字段(数字)witch是用户帖子的总数。我认为在模型中做这件事是件好事,但我无法在ActiveRecord结果中访问它。我怎样才能做到这一点 ? –

+0

你应该看看'rabl'宝石。一个railscast也在那里。 – manoj2411

+0

这就是我需要的东西。只需在我的rabl集合中添加一个节点并且它可以工作; p'node(:number){| user | user.posts.count}' –