渴望加载多个关联

时间:2013-03-02 17:34:32

标签: ruby-on-rails-3 activerecord ruby-on-rails-3.2

我有三个相关的对象:

class Site < ActiveRecord::Base
    belongs_to :program
end

class Program < ActiveRecord::Base
    belongs_to :user
    has_many :sites
end

class User < ActiveRecord::Base
    has_many :programs
end

在我的Sites index视图中,当循环浏览我的所有网站时,我想调出EditDestroy按钮,但前提是current_user拥有该网站:< / p>

- if current_user == site.program.user || current_user.try(:admin?)
  = icon_link_to "edit", 'Edit', edit_program_site_path(site.program, site), :class => "btn btn-primary"
  = icon_link_to "trash", "Delete", site, confirm: 'Are you sure?', method: :delete, class: 'btn btn-danger'

此代码失败,因为程序和用户对象为零。

我知道在我的控制器中我需要以下内容:

@sites = Site.includes(:programs).all

哪会解决访问site.program的问题,但我不确定如何也可以包含user

如果认为当前架构不正确,则可以接受模型更改。

感谢。

1 个答案:

答案 0 :(得分:1)

使用,

Site.joins(:program).where('programs.user_id=?', current_user.id).includes(:programs).all
相关问题