开发者

Finding records in Rails (confused over what approach to take)

A user has many tasks.

In the a tasks controller view, need to show tasks for the user. (one view for various statuses - active,assigned,closed etc)

What's the "right" way for getting a list of the tasks, say for the status = active ?

#class method on Task; called from TasksController
Task.fin开发者_高级运维d_for_user(current_user, :active)

#instance method on user; called from TasksController
current_user.find_tasks :active (user model instance)

#the "common" way that is used in controllers and in many examples/articles
current_user.tasks.find(:where => :status = :active)  #Note the "where" part here is pseudo-code (not tested it)


Using the association is how I've been trained to do it. Always worked fine, and lets Rails take care of the SQL without any additional code from me.

So current_user.tasks.where(:status => :active), or you could create a scope.

in app/models/task.rb:

class Task < ActiveRecord::Base
    scope :active, :conditions => { :status => :active }
    ...
end 

and call current_user.tasks.active in your controller

also might wanna take a look at the documentation which contains a lot of other nice tips

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜