My New Rails Application: MVC

Posted by Rene Cocom on March 15, 2020

My Rails application used all of my Ruby knowledge I have learned. The scope of what felt benefits me the most was my consistent review of the MVC structure. The MVC structure is amazing and it helps Rails show its magic when you apply helper methods that respond across the Model, Views, and Controller. To start talking about the challenges was remembering the Active::Record rules of how to retrieve data and use that knowledge in my has_many through relationships. Before when dealing with models I would explicitly have methods do the heavy lifting, but now I had helper_methods that are the same code I would have written.

The use of scope method was different than what I had imagined because “where” was still used but it was removed from a block and placed in a single line method with the leading word scope. The has_secure_password and validation where all very convenient and self-explanatory. Although the Model was the quickest to implement, I also saw that careful planning of the database was important. The relationships of has_many, has_many_through and belongs_to need to be seen from a graphical point of view, otherwise, you’ll be trying to remember what goes where and who receives a foreign_key. The way I did it was I had a graph of the model relationships with all of their attributes and saw the connections by connecting them with lines that followed the flow of the design of the app. The table with belongs to will have the use_id and other_model_id these are helpful with nested resources and form builders like a <%= fields_for :param_attr %>. All of the foreign_key data will relate through this system user has_many :posts and user has_many :comments through: post so the post and comments here are plurals the same for users if it were in the Post Class. The comment class will only belong to one of each here so it says belongs_to :user and belongs_to :post the post and user are singular here.

When naming models they are singular and the controllers and views are plural, this is part of Rails naming convention for the Model-to-Model Relationships. The Controller faces the logic from your model and redirects to the view. They have a set amount of methods called actions that cover most of what you will need when building out CRUD functionality. The CRUD stands for Create, Read, Update, Destroy, each of them has set actions that are needed to be effective for example the edit and update would be needed to effectively complete a task. The way that the controller action creates a new user would be through using the Models data about the user and creating an instance of a User object by User.new. Next, the User.new(user_params) are “parameters”, referring to either HTML being query string parameters, or the second is referred to as POST data. If you wont to receive the data from the users input the data like params[:status] == 'activated' will be sufficient to show a list of activated post, the second would params[:user_name] would be reliant of the HTML form with the user permits.

Know your relationships.

When creating new models or controllers it’s best to use generators, generators will create along with the model, for example, a migration table for the UsersClass, and a view for the controller when generating either. When creating a rails app there are many ways to generate a new rails app and its directory such as scaffolding which auto_generates a set of models, views, and controller for a single database table. The customization is not lost when using a generator, instead, you have full control over what is generated. When generating a view it is simple to do and then you can fill in your views with a new.html.erb which mirrors our new action within the controller. So, if the user create action is directed to a new Post create action the new.html.erb will have a form_for @post that will route the URL for the user input via the params of the Post controller. The input will then populate the database of the PostCreates table and .save. The view is what the user will interact with and you must have your redirect flow comprehensive enough so that the user isn’t spending too much time searching. The index path will have a filter of sorts because you will want to produce a list of comments on each post, with this iteration the @post.comments.each will take control of the nested forms and resources to show the user what they want.

The Views can have a verity of alterations including helpers, drop_down list, check_boxes, email input fields, and more. When planning out your view paying attention to what you know about how active record works when looking for <%= @post.comments.status%> that this erb tag will produce what has been stored in the table by the user if ever needed. Talking about associations is better when describing the urls. The url 'users/:user_id/comments' is written as user_comments_path aka commments#index, this example shows a nested resource, and how we use it when redirecting. The url looks into the user’s index, associated foreign_key, and then the comments index. This example is in the comments index because comments are the join table for both posts and users. Furthermore, the url can be rendered as in render 'users/:user_id/posts' but the convention is redirect_to user_posts_path, also it is much more readable.

Take your time.

The important thing to remember while using MVC is to take time to plan your next move because Rails is working alongside you. So, if you are not routing correctly of the relationships are not embedded in your memory make a graph to avoid further complications. Most of my issues where these, I have seen much of the problem caused by not know how my relationships worked, even when in the byebug/binding.pry console. Having a graphic will constantly remind you to search all users by User.all then User.errors.messages just to see that you forgot to @user.save after you made a new user. The last thing I’ll mention is the SessionsController, this controller is important because it will log in to your user. The SessionsController will reduce the CRUD format and use mostly the home, new, create, and destroy. The home action is my mine way of having a welcome#home for the root page so the user will have a start page where they have the options to signup or login. Once the user has signed up the user will be logged into session data and cookies. This is not a database for sessions, but will use the session[:user_id] = user.id to store the user for the next time they return to the site. The user_name, email, and password are stored, and the password_digest will filter the password and authenticate it for when the user logs in again to the other user’s credentials.

Learning MVC is fun and will help you see how database CRUD and sessions cookies work, I happen to find it challenging as well which is why I find learning it so fascinating. There is more to include because the Rails Framework is extensive, but this covers some details about how the basic user interaction works and how great the MVC is for building the web application you’d want. Finding a pace that works for you will help return results, looking back at documents, and reading through the code carefully works. If there are errors, use them to sort out the problem before asking for help because a lot of how you learn is through frustration at least for me. Most of my errors would be undefined method errors and I would know to look into a console to see what that variable returned, if it was nil then I new that could narrow it down to a few possibilities and then retrieve the result. Trial and error help with the process and staying focused on the results.