2015-11-01 81 views
1

我收到任务:完成的活动记录

添加一个方法叫做得到完成计数的用户模型类,其中:

•接受用户作为参数

•确定TodoItems数量用户使用聚合查询功能

完成

- (提示:你正在寻找与特定用户相关TodoItems的计数,其中完成:真)

•返回

class User < ActiveRecord::Base 

    has_one :profile, dependent: :destroy 
    has_many :todo_lists, dependent: :destroy 
    has_many :todo_items, through: :todo_lists, source: :todo_items, dependent: :destroy 
    validates :username, presence: true 

    def get_completed_count 
     todo_items.length 
    end 

    end 

有谁可以解释一下什么是完整的方法不计?

谢谢,迈克尔。

+0

你有什么问题吗? – matanco

+0

如何完成任务.... –

回答

7

所以你写了“接受用户作为一个参数”,所以你应该做到以下几点:

def self.get_completed_count(user) 
    user.todo_items.where(completed: true).count 
end 

,你可以把它叫做:

User.get_completed_count(user) 

,但上面的代码不会使任何意义,因为更好的是做它作为实例方法:

def get_completed_count 
    self.todo_items.where(completed: true).count 
end 

此代码将返回相同的结果只是在实例。

可以称之为:

User.find(id).get_completed_count 

我假设的TodoItem已完成的布尔(更好地创造一个范围和使用方法,而不是where(completed: true)这里面范围)。

+0

史诗般的答案,做得很好。 –

+0

matanco,谢谢+1。 –

+0

我想我真的希望将它实现为一个ActiveRecord关联,并合并在ToDoItem的作用域中以限制完成的项目。所以'User.find(id).completed_to_do_items.count'。例如,这将有利于在代码的单个点中表达逻辑,同时还允许在索引页面中进行热切加载。很高兴看到答案中包含这种方法。 –

-1

你会希望有一个ActiveRecordAssociation Extension

#app/model/user.rb 
class User < ActiveRecord::Base 
    has_many :todo_items, through: :todo_lists, source: :todo_items, dependent: :destroy do 
     def completed 
     where(completed: true).count 
     end 
    end 
end 

这将允许您拨打:

@user = User.find params[:id] 
@user.todo_items.completed #-> 5 

为了给上下文Mantanco的答案,直接回答你的问题是使用类方法。这是与类调用的方法:

#app/models/user.rb 
class User < ActiveRecord::Base 
    def completed user 
     user.todo_items.where(completed: true).count 
    end 
end 

这是使用称为:

@user = User.find params[:id] 
@user = User.completed user 

什么你需要实例方法 - 这对一个实例奏效的方法类别:

#app/models/user.rb 
class User < ActiveRecord::Base 
    def completed_items 
     todo_items.where(completed: true).count 
    end 
end 

这将允许您拨打:

@user = User.find params[:id] 
@user.completed_items 

您可以在这里看到类和实例方法之间的区别:

def get_completed_count(user) 
     user.todo_items.where(completed: true).count 
end 

感谢所有的回复: http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

0

答案对我来说是。

+0

这是帮助我的正确答案......感谢所有人。 –

0

其实,这是我今天早上没有和它完美的工作对我来说

def get_completed_count 
     todo_items.where(completed: true).count 
end 
0

下面的代码为我工作。

高清get_completed_count

self.todo_items.where(完成:真).Count之间