Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

sql - rails multiple level include on nested association

I have 3 tables, comments, users, and images.

I'm trying to formulate a query that will product arrays of comments on a post that includes the commentator's information and a avatar.

The avatar is stored in the images table, while the users table contains the user info plus a reference id to the image object that stores the users avatar.

Each comment has a author id that is referencing an object in the user table.

This is what I have so far

@comments = Comment.all(:include => [:user => :images], 
            :conditions => {
              :source => p[:source], 
              :source_id => p[:id], 
              :users => {:id => p[:user_id]}, /* if this result is *user */
              :images => {????} /*essentially i need images.id = *user.profile_id */
              })

Can't get the image part to work, can someone show me how?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is what I got working at the end

class User < ActiveRecord::Base
    belongs_to :image, :foreign_key => "profile_id"

class Image < ActiveRecord::Base
    has_one :user

class Comment < ActiveRecord::Base
    belongs_to :user

@comments = Comment.all(:include => [{:user => :image}, :like, :flag], 
            :conditions => {
              ...
              })

This works but if anyone can tell me if its the proper way to do this it would be great


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...