How to organize the Rails structure - ruby-on-rails

I have a very big question about Rails. Suppose that we need to create a web site about blogs, we allow user registration and the user has their own management interface which make it possible for them to add, delete, edit, and select the article and comment. The operation on the article and comment might be used in other positions in the future.
So we have a article model and a comment model.
Now we create a users controller:
class UserController < ApplicationController
def articleList
end
def articleSave
end
def articleUpdate
end
def articleDestroy
end
def articleEdit
end
def articleAdd
end
def commentList
end
def commentDestroy
end
def commentEdit
end
end
But it din't look good, and when the user management control has many features, this user controller will be very big. Should I create an article controller and comment controller to process the request? Just separated into the article controller is like this:
class ArticleController < ApplicationController
def list
end
def save
end
def update
end
def destroy
end
def edit
end
def add
end
end
Comment controller is as follows:
class CommentController < ApplicationController
def list
end
def destroy
end
def edit
end
def update
end
end
I don't know how to organize the structure.

I would have separate controllers for each of the Users Articles and Comments, but nest them with Comments inside Articles, and Articles inside Users. This seems to fit the relationship between the concepts as you've described them
See
http://www.sentia.com.au/blog/when-to-use-nested-controllers-in-your-rails-apps
and
http://guides.rubyonrails.org/routing.html#nested-resources
for more on nesting controllers.

Related

Decorator/Presenter/Exhibits and helpers

I have read:
Concerns, Decorators, Presenters, Service Objects, Helpers, Help me Decide
and trying to figure out the difference between presenters, view objects, decorators, exhibits, and helpers.
I have multiple active record models that I need to display in a view using the show method.
Examples of what I need to display are:
ClassModule SomeTypeOfPattern
def name
User.name
end
def car_name
User.car.listing.car_name
end
def car
User.car
end
def car_marketing
User.car.marketing
end
# AND 20 to 30 other similar delegations/methods from 4 related tables
end
So if I delegate these relationships, what should the class/module be called? A presenter? Decorator? View Object? I am so confused by all these terms, but want to follow convention.
The example you are showing looks like a Presenter to me.
A presenter is an object that presents other information with its own interface.
If you changed what you have just a little, you could use it like this:
presenter
class UserCarPresenter
attr_reader :user
def initialize(user)
#user = user
end
def name
user.name
end
def car_name
user.car.listing.car_name
end
def car
user.car
end
def car_marketing
user.car.marketing
end
end
controller
class CarsController < ApplicationController
def show
#user = UserPresenter.new(user)
end
end
view
<h1><%= #user.name %></h1>
<h2><%= #user.car_name %></h1>

How do I get acts_as_votable results for a specific model?

I'm working with the acts_as_votable gem for a project that will allow users to 'like' their favorite courses and their favorite guides. The favorited guides will then show up on one page and the favorited courses on another. I'm having trouble with retrieving model specific results in my controller below is code that works but is not scoping to a specific controller.
class FavoritesController < ApplicationController
def guides
end
def courses
user = current_user
#courses = user.find_up_voted_items
end
end
This is the only code I've gotten to work, I realize there is nothing in the controller currently to narrow down the results to a specific model but I wasn't able to get anything I tried to work.
From the acts_as_votable docs:
Members of an individual model that a user has voted for can also be
displayed. The result is an ActiveRecord Relation.
#user.get_voted Comment
#user.get_up_voted Comment
#user.get_down_voted Comment
https://github.com/ryanto/acts_as_votable
So in your case I would use:
class FavoritesController < ApplicationController
before_action :get_user, only: %i[guides courses]
def guides
#guides = #user.get_up_voted Guide
end
def courses
#courses = #user.get_up_voted Course
end
private
def get_user
#user = current_user
end
end

Rails: sharing a controller across two models

I have two models:
Student
Classroom
Both of them have an action that does the same exact thing: it shows a report of daily activity. That is:
/students/1
/classrooms/1
Grabs activity for the model in question and displays it on the page.
In an attempt to dry this up, I created a ReportsController which extracts all the common logic of building a report.
If I leave the routes like this:
/students/1/report
/classrooms/1/report
Then I can have the ReportsController#show action look for params for :student_id or :classroom_id to determine which model type it is dealing with (for purposes of querying the database and rendering the correct view).
But I would prefer the URLs to be cleaner, so I also changed my routes.rb file to pass the show action for these models to the reports#show controller action:
resources :students, :classrooms do
member do
get :show, to: 'reports#show'
end
end
This works, but I can no longer depend on params to identify which model to work with and which view to render.
Question: should I parse request.fullpath for the model? Or is there a better way to make a shared controller understand which model it is working with?
Routing both show methods to the same controller method for code reuse is somewhat like banging a nail in with a dumptruck.
Even if you can find the resource by looking at the request url you would start splitting the ResortsController into a bunch of ifs and switches even before you got off the ground.
One solution is to add the common action in a module:
module Reporting
extend ActiveSupport::Concern
def show
# the Student or Classroom should be available as #resource
render 'reports/show'
end
included do
before_action :find_resource, only: [:show]
end
private
def find_resource
model = self.try(:resource_class) || guess_resource_class
#resource = model.find(params[:id])
end
# This guesses the name of the resource based on the controller name.
def guess_resource_class
self.class.name[0..-11].singularize.constantize
end
end
class StudentController < ApplicationController
include Reporting
end
# Example where resource name cannot be deduced from controller
class PupilController < ApplicationController
include Reporting
private
def resource_class
Student
end
end
self.class.name[0..-11].singularize.constantize is basically how Rails uses convention over configuration to load a User automatically in your UsersController even without any code.
But the most important key to DRY controllers is to keep your controllers skinny. Most functionality can either be moved into the model layer or delegated out to service objects.
I would put the common logic in the Event Model:
#Event Model
class Event < ...
def self.your_event_method
#self here will be either student.events or classroom.events
#depending on which controller called it
end
end
class StudentsController < ...
...
def show
student = Student.find(params[:id])
student.events.your_event_method
end
end
class ClassroomsController < ...
...
def show
classroom = Classroom(params[:id])
classroom.events.your_event_method
end
end

Rails file setup for a control panel?

How do you setup your views, controllers and routes?
One controller for everything the control panel does, or many?
Firstly, let's try to think how we would view the various panels. Let's say our control panel is pretty simple. We have one panel to show all the users who have signed-up and can CRUD them, and another panel to show all of the images that have uploaded, and we can carry up CRUD on those too.
Routes:
scope path: 'control_panel' do
get 'users', to: 'panels#users', as: :panel_show_users
get 'photos', to: 'panels#photos', as: :panel_show_photos
end
Controller:
class PanelsController < ApplicationController
def users
#users = User.all
end
def photos
#photos = Photo.all
end
end
View file structure:
panels
|_ users.html.erb
|_ photos.html.erb
Okay, now I don't see any problems with that, to simply access the panels and populate the views with data. Do you see any problems?
Here is where I'm sort of at a cross roads though. What should I do when I want to Created Update and Delete a user/photo? Should I put them all in the PanelsController?
class PanelsController < ApplicationController
before_action :protect
def users
#users = User.all
end
def update_user
#user = User.find(params[:id])
#user.update(user_params)
end
def photos
#photos = Photo.all
end
def update_photo
#photo = Photo.find(params[:id])
#photo.update(photo_params)
end
private
def protect
redirect_to root_url, error: 'You lack privileges!'
end
end
While this would result in a large PanelsController, it would feel good to be able to execute that protect action and just one controller hook. It would also mean the routes would be easy to setup:
scope path: 'control_panel' do
get 'users', to: 'panels#users', as: :panel_show_users
post 'user', to: 'panels#update', as: :panel_create_user
get 'photos', to: 'panels#photos', as: :panel_show_photos
post 'photos', to: 'panels#photos', as: :panel_create_photo
end
I should use resource routes here?
Like I say, this will result in a huge panels controller, so I was thinking it may be better to have a separate controller for each resource and then redirect to panels views?
Routes:
scope path: 'control_panel' do
resources :users
resources :photos
end
Controllers:
class UsersController < ApplicationController
def index
end
def show
end
def new
end
def create
end
def update
end
def destroy
end
end
class PhotosController < ApplicationController
def index
end
def show
end
def new
end
def create
end
def update
end
def destroy
end
end
Still some quirks though. I have my Users#index action there, but what if I have two routes that return an index of all users? In the control panel, but also, when people are searching for another user, for example. Should I have two routes in the User controller? def public_users and def control_panel_users? That may be the answer. Could setup a hook to run #users = User.all in both of them, but redirect to a different location, and not have the protect method redirect them.
How should I protect these routes from non-admins? Should I move my protect method into the the application controller? Wouldn't this be a bit fiddly to setup?
class ApplicationController < ActionController
before_action :protect
def protect end
end
class StaticController < ApplicationController
skip_before_action [:home, :about, :contact]
def home
end
def about
end
def contact
end
end
But that is my question. 1 control panel controller or no control panel controller.
I really wish there was more advanced tutorials out there :( Billions of books on CRUD, MVC and things, but nothing on advanced things like control panels and AJAX...
Don't have a control panel controller. And to protect stuff from non-admins, use namespacing - read more about it here: http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing
You can protect your 'admin'-namespaced controllers with authentication, and have the non-namespaced controllers open to the public (or open to non-admin users)
With regards to your def public_users and def control_panel_users question, you could just have two def index methods - one in the non-namespaced controller, and one in the admin-namespaced controller. They would each do different things.
So, you'd have 4 controllers in total:
2 non-namespaced, one for users, one for photos (containing all public stuff)
2 admin-namespaced, one for users, one for photos (containing all control panel stuff)
If you wanted, rather than using 'admin' as the namespace, you could use some other term you prefer - like 'panel'. 'Admin' is pretty conventional though.

cancan for new action

I added new action to my restful resources how can I authorize it with cancan.
Pages controller:
load_and_authorize_resource
def index
end
def show
end
def new
end
def create
end
def edit
end
def update
end
def destroy
end
def mynewaction
end
Ability model:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
can :create, Page
can :mynewmethod, Page #does it work?
end
Yes I believe it works for things other than the CRUD methods, although this is just from looking at some of the documentation, check out here and the actual documentation by ryanb here.
You should especially look at that first link that says that the load_and_authorize_resource will apply to all methods in the controller, even ones other than the usual CRUD ones.
I think the easiest way is just to test it out, does it authorize correctly when you fire it up? Nothing better than to try.

Resources