I’m writing a rails app that has a model called ‘User’ and a model called ‘Page’. Users can have multiple pages, and users can also authorize other users to view their pages. To describe this in rails, I’m using a has_many, :through relationship with a third model I’ve created called ‘Authorization’. The models look something like this:
class User
has_many :pages, dependent: :destroy
has_many :authorizations, dependent: :destroy
has_many :viewable_pages, :through => :authorizations, :source => 'page'
end
class Page
belongs_to :user
has_many :authorizations, dependent: :destroy
has_many :authorized_viewers, :through => :authorizations, :source => 'user'
end
class Authorization
belongs_to :page
belongs_to :user
end
As far as back-end functionality goes, this has been working perfectly for me. I’m a little stumped when it comes to rendering these relationships and allowing the client to modify them.
I have a controller for Page, and when ‘show’ is called, I render the page. When I render the page, I also want to render the page’s list of authorized_viewers and allow the user to modify that list with AJAX commands. Essentially, I want to do something like this in the ‘Page’ layout:
<% @authorized_viewers.each do |v| %>
<li><%= v.email %><%= link_to 'delete', authorization, method: :delete, remote: :true %></li>
<% end %>
I’m not quite sure how to reference the authorization itself, and not the authorized_viewer. I just want to delete the relationship, not the user. I’m also not sure if I should make a controller for ‘Authorization’ in order to create methods like ‘destroy’, which I can modify and give them the ability to respond to AJAX calls. Authorizations will only be rendered on the ‘Page’ view, so it doesn’t seem to make sense generate a whole scaffold with views for Authorizations. What’s the best way to approach this?
I realize this is a very long question. Any insight would be tremendously appreciated!
An easier way to show the authorizations in the view would be (assuming you are using nested routes for the page/authorization relationship, modify the path argument otherwise):
It would be best to create a controller for authorizations if you are going to be performing actions directly against that object (such as create/destroy). You don’t have to create any views if this is always going to be done over AJAX. This keeps all of your functionality organized, and will ensure that any interactions relating specifically to authorizations reside in the authorizations controller. Avoid creating a scaffold, instead just create the controller with two actions:
createanddestroy