ruby on rails 3 - How to change these SQL statements with multiple joins into ActiveRecord style queries? -
artists have_many :posts, posts have_many :comments. artists follow other artists through "inspirations". (i want build facebook-type news-feed show recent activity such as:)
- someone has posted new comment on 1 of posts
- artist whom follow has added new post
- artist whom follow received new comment on particular post
my idea 3 independent queries above, , concatenate final messages desc date. here how 3 queries, using methods in artist class:
def comments_on_my_posts comment.where(:joins => :post, :conditions => {:posts => {:artist_id => 1}}).order("comments.updated_at desc") end def posts_from_my_follows #select * posts inner join inspirations on posts.artist_id = inspirations.author_id inspirations.artist_id = self.id # end def comments_on_posts_on_people_i_follows # select * comments inner join posts on comments.post_id = posts.id inner join inspirations on posts.artist_id = inspirations.author_id inspirations.artist_id = self.id end
i prefer not use sql directly if don't have to. don't know how multiple joins using activerecord.
for reference, here models:
class artist < activerecord::base has_many :posts, :dependent => :destroy, :order => 'updated_at desc' has_many :inspirations has_many :follows, :through => :inspirations, :source => :inspiration end class post < activerecord::base belongs_to :artist has_many :comments, :dependent => :destroy, :order => 'updated_at desc' end class comment < activerecord::base belongs_to :author, :class_name => "artist", :foreign_key => :author_id belongs_to :post end class inspiration < activerecord::base #the follower belongs_to :artist #the followee belongs_to :inspiration, :class_name => 'artist', :foreign_key => :author_id validate :disallow_self_referential_following validates_uniqueness_of :artist_id, :scope => :author_id def disallow_self_referential_following if artist_id == author_id errors.add(:author_id, 'cannot follow self') end end
the rails 3 query interface joins documented here: http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-the-joined-tables.
with rails 3 can chain activerecord calls build query want. sure watch development log file see queries being generated. (unless you're on rails 3.1 version). can add .to_sql
call end of query see generates.
Comments
Post a Comment