Setting up controller for nested and non-nested access - model-view-controller

I have two models, Company and Contact.
I'd like to have the following routes (among others):
http://example.com/contacts (lists
all contacts)
http://example.com/company/1/contacts
(lists all contacts for company #1)
For sake of simplicity, the views will be identical except for the page title and breadcrumbs.
What is the best way to setup my ContactsController? Are these two different actions? Would my approach change if in the future I wanted to handle a 3rd type of route such as http://example.com/salesregion/1/contacts?

I'm not very familiar with ruby on rails, but, using common MVC practice, this is how I would go about this solution:
Create a route that is something like this: Contacts/{type}/{id}
Where type can be (company, salesretion, etc.) and id would be the id of that given model. In theory then simply filter the query based on the given type.
Hope this helps.

Related

Polymorphism table divided on 3 controllers

I am building an application where you can write reviews on a company their profile. This is normally a one to many relation, but in the application, you can also write reviews on an apartment page and arrangements page. So I have 3 different pages to add the review functionality. Obviously, the user can edit and delete reviews too.
the reviews table is polymorphic. So you have a field with reviewable_type and reviewable_id
Now I was thinking to make a ReviewController to reduce code duplication. The problem I am facing right now is that I need to display the reviews on these 3 different pages, but I don't want to include the same code in every controller (ApartmentController, ArrangementController, CompanyController).
What's the best way to achieve this solution without duplicating to much code.
I was thinking to put a special class outside the MVC pattern, but I want to keep is as close to the MVC pattern.
Also, I thought of putting another method in the 3 controllers, but then again there's going to be code duplication.
You can use the traits to achieve this.
Make a new trait ReviewTrait and put the code in it and use in all the controllers.
You can find more traits here Link.
Create a modal function inside the company modal lets called it Reviews, which takes the review type as a parameter.
Now call the modal function Reviews with review type in the ApartmentController, ArrangementController, CompanyController.

what exactly is a RESTful resource web api? [duplicate]

Dumb question but I have some lingering confusion of what, exactly, a "resource" is in Rails. The term is used everywhere but I get a funny feeling it might be being used rather loosely. It's referenced in the model, the controller and, quite literally, in routes.rb.
Is it the specific route? For example, map.resources maps the 7 RESTful "resources". So an example of one resource would be the call to, say, the index action of a particular class's controller?!?
Is it a reference to the whole page/object being retrieved? or perhaps, more narrowly, a database table? or the row being retreived?
Is it something else?
Anyway, hopefully someone can set me straight...
Any object that you want users to be able to access via URI and perform CRUD (or some subset thereof) operations on can be thought of as a resource. In the Rails sense, it is generally a database table which is represented by a model, and acted on through a controller.
For example, you might have a User resource (with a users table in your DB). This is represented by a User model, is mapped to users_controller with map.resources :users (which then generates routes like /users (a collection of User resources) and /users/1 (a specific User resource).
You act upon those resources by using the appropriate HTTP method when making calls to those resources. POST to the resource collection (/users) creates a new record; GET retrieves a list of resources (/users) or a specific user (/users/1). PUT updates a specific user (/users/1/), and DELETE destroys that user. The URLs are the same, but the result (and controller action) may be different based on the HTTP verb. The idea, though is that /users/1 always means "I'm interacting with the User that has ID #1", regardless of the action.
Here's a good article discussing how most developers think that "Resource" is synonomous with the database table, the argument, I guess, being that mapping to the resource is mapping the controller to that database table (or, with ActiveResource, to another REST url).
Basically, I think a "resource" is "persisted data." map.resources maps the 7 RESTful actions to a particular suite of persisted data.
But I haven't thought about it too much in depth. Good question!
I think they probably mean it in the general web sense, i.e., Resource (Web):
the referent of any Uniform Resource Identifier
I don't think it has anything to do with database tables.
open your model folder, that is a hint of what resources you have!
example: users, pictures, comments...
A lot of people here say that resources refer to the database tables you have. It might be true sometimes but not necessarily true always. I could give you a lot of examples where you don't have a corresponding table in your database for a particular resource. Hence asssociating it with tables is rather wrong.
I would define a resource as a route which maps to related requests. So instead of declaring separate routes for the actions you want to do you can simply declare them using a resourceful route.In Rails, a resourceful route provides a mapping between HTTP requests and URLs to controller actions.
So say you define resources :users in config/routes.rb. You can now use a number of helpers to the controllers in your application like edit_user_path which returns users/edit .
Here's a good link: https://api.rubyonrails.org/v5.2.1/classes/ActionDispatch/Routing/Mapper/Resources.html
Which basically says: Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index, show, new, edit, create, update and destroy actions, a resourceful route declares them in a single line of code:
resources :photos

For a blog: should I define CRUD functions for categories and tags in ArticlesController or create controllers of their own?

Laravel beginner here. So as you can guess I am creating an blog where user can create an article under a category and have different tags.
I have defined plenty of routes for articles already.
public/article/{id}/show
public/article/{id}/delete
public/article/create
So if I define a CategoriesController and a TagsController, I'm going to have to to define all of these CRUD methods in it and the routes too as:
public/categories
public/categories/{id}/delete
public/categories/create
public/tags
public/tags/create
public/tags/delete
Should I move ahead and build it this way or is there a better way to do this?
If you're talking about an administration system, you need CRUD to maintain your tags table.
In a curated system, where tags are controlled, the process of adding tags involves finding existing tags, perhaps asynchronously. You could utilize id's behind the scenes, assuming you have a relational database.
As people type some characters into the tagging portion of the UI, the system asynchronously finds a matching tag and displays it. Once that has occurred, there is no reason not to use the tag ID, and in that case, having a full set of tag routes is useful, but is not essential unless you have curated tags. For example, even if you want to use relational keys to store the relationship, you probably just need a search function which takes a tag string, searches for the matching tag, and returns that matching data.
In some systems, whatever tags are provided are added on the fly, but even in those cases, they are usually at least conformed. For example, you might want to eliminate bad words, mixed case, punctuation etc.
In short, if you need to maintain a tag table, then you will want CRUD for tags. If not, then adding tags, would just be part of the dataset that is operated on probably as part of the POST, when an article is created.
Also, just logically speaking, you shouldn't have a route for /public/article/{id}/create. It should just be /public/article/create
here are some good directions to look for
use RESTful Resource Controllers so you don't have to define each and every CRUD operation seperately. It would make your routes and controllers neat and clean. plus RESTful its a recommended nice way.
RESTful Resource Controllers
Another way is patterns. use good patterns for designing structure and behavior. here are some good reads. have a look
https://www.ibm.com/developerworks/library/os-php-designptrns/
http://shawnmc.cool/the-repository-pattern
https://sourcemaking.com/design_patterns
one nice and common way is to use repository pattern. In repository pattern the repositories work in between models and controllers.
"Repository commonly refers to a storage location, often for safety or
preservation." - Wikipedia
This would make your controllers and models simple and clean.

Generating Navigation for different user types, MVC, PHP

I have this idea of generating an array of user-links that will depend on user-roles.
The user can be a student or an admin.
What I have in mind is use a foreach loop to generate a list of links that is only available for certain users.
My problem is, I created a helper class called Navigation, but I am so certain that I MUST NOT hard-code the links in there, instead I want that helper class to just read an object sent from somewhere, and then will return the desired navigation array to a page.
Follow up questions, where do you think should i keep the links that will only be available for students, for admins. Should i just keep them in a text-file?
or if it is possible to create a controller that passes an array of links, for example
a method in nav_controller class -> studentLinks(){} that will send an array of links to the helper class, the the helper class will then send it to the view..
Sorry if I'm quite crazy at explaining. Do you have any related resources?
From your description it seems that you are building some education-related system. It would make sense to create implementation in such way, that you can later expand the project. Seems reasonable to expect addition of "lectors" as a role later.
Then again .. I am not sure how extensive your knowledge about MVC design pattern is.
That said, in this situation I would consider two ways to solve this:
View requests current user's status from model layer and, based on the response, requests additional data. Then view uses either admin or user templates and creates the response.
You can either hardcode the specific navigation items in the templates, from which you build the response, or the lit of available navigation items can be a part of the additional information that you requested from model layer.
The downside for this method is, that every time you need, when you need to add another group, you will have to rewrite some (if not all) view classes.
Wrap the structures from model layer in a containment object (the basis of implementation available in this post), which would let you restrict, what data is returned.
When using this approach, the views aways request all the available information from model layer, but some of it will return null, in which case the template would not be applied. To implement this, the list of available navigation items would have to be provided by model layer.
P.S. As you might have noticed from this description, view is not a template and model is not a class.
It really depends on what you're already using and the scale of your project. If you're using a db - stick it there. If you're using xml/json/yaml/whatever - store it in a file with corresponding format. If you have neither - hardcode it. What I mean - avoid using multiple technologies to store data. Also, if the links won't be updated frequently and the users won't be able to customize them I'd hardcode them. There's no point in creating something very complex for the sake of dynamics if the app will be mostly static.
Note that this question doesn't quite fit in stackoverflow. programmers.stackexchange.com would probably be a better fit

Lost in a simple MVC case - how do I return multiple Users?

I'm not sure which title would be more descriptive, so I kept it this way. I feel kinda lost in the world of MVC.
FYI: I use PHP, but that doesn't seem of much importance in this particular case.
My problem is as follows:
I have a UserController containing the following methods:
login
new
show
overview
Then I have my UserModel, containing - in this case - roughly the same methods:
login
create
fetch
The problem is: what do I keep my user data in once fetched from the database (or XML feed, or webservice, or whatever...)? I thought of a User 'business object', containing all (relevant) properties from the database. Then, when fetching the users from the database, I instantiate a new User object for each user I fetch. If only 1 user returned from the search, I return only the User object. If more users get returned, I instantiate a UserCollection object containing all User objects - in which case I can iterate over them, etcetera.
Is that a correct way of dealing with users in MVC?
And then: imagine I made an overview of 10 users. 5 of them get edited at once - imagine a status modification using checkboxes. How do I process the changes? Do I loop over all changed User objects and store them back in the database? Then it would start to look like an implementation of the Active Record Pattern, something I'm told not to use.
I hope someone can clarify which classes and/or methods I'd need to solve this 'architectural' problem.
Since it is a rather lengthy discussion. I will give the link to an article that I have written on MVC, trying to explain it in simple terms. You may want to take a look at it.
What is MVC pattern about?
If I understand correctly, your UserModel is a bit off;
the Model part of MVC is intended as a programmatic representation of the real world model.
Meaning- it represents all the properties and actions of the real-world subject. The classic example is the Car class, which has properties such as Wheel, CurrentSpeed, and actions such as GoForward(), GoReverse() etc..
So, in your case, I think your model should be what you described as a 'user business object'.
Your controller would be responsible for fetching the UserModels from storage (or wherever), and updating them back.
your workflow would be something like this:
View would call the Controller's GetUsers.
Controller goes to storage, and fetches a list of UserModels.
Controller returns them to the view.
View displays them in some way.
And the other way around for updating.
The UserModel class would be responsible for logic that pertains to individual users (for example- ChangePassword()).

Resources