rails multiple level include on nested association

穿精又带淫゛_ 提交于 2019-12-13 05:15:19

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/18473529/rails-multiple-level-include-on-nested-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!