Reputation: 2306
I have three objects which are related as so:
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
In my Sites index
view, when looping through all of my sites I want to displiay Edit
and Destroy
buttons, but only if the current_user
owns the site:
- 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'
This code fails because the program and user objects are nil.
I know that in my controller I need something like the following:
@sites = Site.includes(:programs).all
Which would solve the problem of accessing the site.program
, however I am not sure how I can also include the user
.
Model changes are acceptable if the current schema is considered incorrect.
Thanks.
Upvotes: 0
Views: 321
Reputation: 2891
Use,
Site.joins(:program).where('programs.user_id=?', current_user.id).includes(:programs).all
Upvotes: 1