Rails 4.2如何为动态条件急切加载/预加载相关对象

时间:2017-01-20 16:33:26

标签: ruby-on-rails ruby-on-rails-4 activerecord eager-loading

我为Ruby on Rails项目开发引擎。在这里,您可以看到我如何通过动态条件解决急切加载关联对象的问题:

我的模特:

#version.rb  
class Version < ActiveRecord::Base
 class <<self
     attr_accessor :type
     attr_accessor :id
 end
 validates :name, :description, presence: true
 belongs_to :package
 has_many :clustervers,:dependent => :destroy
 has_many :accesses,:dependent => :destroy
 has_many :user_accesses,-> { where(  "who_type= ? AND  who_id=?",Version.type,Version.id) }, class_name: "Access"

end
 #Access.rb
class Access < ActiveRecord::Base
 enum status: [:request,:allowed,:denied]
 validates :version_id, :user_id,presence: true
 validates_uniqueness_of :user_id, :scope => [:version_id]
 belongs_to :version
 belongs_to :user
 belongs_to :who, :polymorphic => true

end

控制器:

def show
  Version.type="User"
  Version.id=2
  @package = Package.find(params[:id])
   @versions = Version.page(params[:page]).per(2).includes({clustervers: :core_cluster},:user_accesses)
   .where(package_id:params[:id])
end

查看:

  for version in @versions
                tr 
                    td  #{version.name} 
                    td  #{version.description}
                    td  #{version.r_up} 
                    td  #{version.r_down}





                        -if version.user_accesses.take
                            p   show attributes
                        -else
                            p   no access
                    td

有更方便的方法吗?是否可以使用原始SQL语句执行此操作? 我需要一些东西来生成这样的SQL条件:         LEFT OUTER JOIN ...在a.id = b.id和CONDITION

0 个答案:

没有答案