ubuntu, ror, jQuery, css, website memo
太嫩, 沒啥心得, 用來紀錄每天學的
2009年11月15日 星期日
include vs joins
http://railscasts.com/episodes/181-include-vs-joins
User.all(:joins => :comments, :select => "users.*, count(comments.id) as comments_count", :group => "users.id")
g = Group.first
Comment.all(:joins => {:user => :memberships}, :conditions => { :memberships => { :group_id => g.id } })
# models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :user
end
# models/user.rb
class User < ActiveRecord::Base
has_many :memberships
has_many :groups, :through => :memberships
has_many :comments
end
# models/membership.rb
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :group
end
# models/group.rb
class Group < ActiveRecord::Base
has_many :memberships
has_many :users, :through => :memberships
#rails does not support nested association
def comments
Comment.scoped(:joins => {:user => :memberships}, :conditions => { :memberships => { :group_id => id } })
end
end
沒有留言:
張貼留言
較新的文章
較舊的文章
首頁
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言