Rails models and controllers - ruby-on-rails

I am new to development. I've read a few books on rails and often times they dive straight into examples. In some examples they generate resources which includes models, views, controllers etc. while in others they generate models only and vice versa. When should controllers be generated?It'd be great if someone could shed some lights to this to help me begin. Thanks.

You should do this tutorial : http://guides.rubyonrails.org/getting_started.html it pretty shows much everything about Rails concisely.
But basically ..
Controllers are files that are the first endpoint to routes. When you type an address in the navbar you end up in a controller first. Then, inside your controller an action is triggered (Show, Index, Update ...).
Actions can be blank it is not a problem. But most of the time there is some logic added. This logic can be loading some data, creating records in the database etc ...
Once the action is completed a view is triggered. This view corresponds to the controller action that has been just been visited. It is usually an ERB file that will eventually produce an HTML file after the server side scripting is completed.
Models sit alongside controllers and views: they handle all the database data. This includes validations for the fields of specific tables (does an uploaded file exceed max size, can a field of a record be blank etc ...). One database table = one model.

The most simple explanation would be :
Controllers talk to your views and models, they take requests from users (when a user is visiting your website, all requests go to the route.rb file, depending on how you set up the route.rb file the requests go to the right controller or directly to views, if you have static pages for example) and create responses.
Models are handling the hard stuff, they communicate with the database and add/remove/edit any new data in the database and provide the controller with the data it needs.
Views are just html files in which you can embed ruby code (views end with the .html.erb extension (erb is for embedded ruby)). They get the data they need from the database through controllers. The controller then sends the right views as a response to the user request.
When are you supposed to create a new view,controller or model? That's very hard to answer without an example. Every application is specific and require a good amount of experience to set up your MVC correctly.
This is the explanation from just another newbee in Rails, so don't take anything I wrote as completely true and correct.
I would suggest you to look into some books for beginners which walk you through the whole process of creating a fully functional website in Rails.
My suggestion would be to check out Michael Hartl's book The Ruby on Rails tutorial or if you want to take a step further and learn Ruby and RoR in detail, visit The Odin Project. Both are completely free and helped me a lot understand how Rails works.

Related

Migrating from rails app to backbone.marionette app

I'm a new in backbone.marionette. I read some guides, but not enough understood how is the MVC structure implemented there.
In rails I'm having structure like this:
app/
assets/
controllers/
models/
views/
config/
environmrnts/
development.rb
staging.rb
production.rb
routs.rb
log/
my view/js files are sending data to controller(during update/create and more), and and also getting data from it. the controller sends requests to model in another rails app, using Api class(that all the models are inherit from it) with net/https.
My questions are:
1. How do I implement the connection with the other app in backbone.marionette?
2. Is the idea of the mvc is the same as in rails? what actually the controller does in marionette?
3. How should my app structure look like?
4. Where should I store config parameters?
It goes through the API you define in the Rails app. Each Backbone model will define a url property to indicate where its data is stored. Then Backbone will take care of the rest (e.g. sending a POST request to the API to create a new model instance in the DB)
The idea is similar, but not the same. In Backbone, the controller and model behave mostly as in Rails apps. Collections are a group of models that you work with to make it easier in your app (e.g. displaying a list of users). Templates are sort of like views in Rails : they define the HTML markup that will get generated. Views in Backbone are very different : they react to the environment (e.g. user clicks, data modification) and drive the app's behavior. This doesn't happen in Rails apps because the page gets rendered and sent back : there is no itnteraction (eacch user click will make the server generate a new page and send it to the user).
It depends. There are many valid approaches, and you can see one here : https://github.com/davidsulc/marionette-gentle-introduction
It depends :-) Quite often, you will stroe them in a simple javascript object.
If you want something to guide you on your journey learning to develop javascript apps, take a look at these :
backbonerails.com uses Rails and Marionette to develop an application
my book on Marionette focuses more on explaining the various bits and pieces of Marionette, as well as how and when to use them
You can see an example of connecting to a different service using an API here : http://www.backbonerails.com/screencasts/loading-views starting at the 6:00 mark. The url property is defined at 9:40, but note that this case requires the url to be different for each collection instance, which might not be true in your case. If all collection instances have the same url, you'd simply define it as a property on the collection "class".

General Questions about Ruby on Rails

Hey guys and merry christmas!
I'm new to ruby on rails and I'm still a little bit confused about some stuff:
When do I need to create a new controller and when not?
I want to create an app with a single searchbox and search through all of the articles. Should I create an Controller for the startpage (the searchbox) and for the search? Should I create controllers for the static pages?
Should I use an Admin interface gem or create my own?
The normal user should now have access to creating articles, just the admin. Should I use one of the admin interface gems or create my own?
Ruby on Rails follows the MVC framework, controllers are classes that contain your actions, so you need to add an action for every function your website will provide.
Technically you could have all actions in one controller but that would be just terrible, so we usually create different controllers to organize your routes and code in a better way.
Follow the Rails guide on controllers.
For the admin interface gem, you could use devise and cancan, they are both very reliable and well tested.
Ruby on Rails is indeed MVC, which means that controllers connect Models to Views. So in general it is good practice to think more resource-oriented: per resource you want found/presented, you create a controller. In your case something like:
ArticlesController : your main view, with the searchbox
PagesController : for static pages, if you need some erb/haml
admin/ArticlesController: for administration of the articles
Now, completely static pages can just as well be placed under the public folder, no need for a controller unless you need some dynamic info to be on the pages (e.g. a total count of articles).
With regards to your search-box: imho this is just a parameter for your index page. E.g. on the index you show the ten most recent articles, and when searching on some term, you show the relevant articles, but on the same controller and the same action.
With regards to the admin interface: yes, use gems like rails_admin or active_admin and it will get you started in no time at all. So definitely do that. But those gems are, of course, very general and might not suit your needs completely. It that should be the case, you can always easily revert later.
HTH.
Merry christmas!
As Khaled suggested Rails being MVC architecture it is always good to have controllers of each page. Even though you might have a static pages for now, but latter when you are trying to make the site dynamic one, then you will be in whole lot confusion of where to add a method for a particular view page.
Generally it is better to use a gem instead of making it from scratch.
You can look into this link which teaches you how to use devise and cancan with twitter bootstrap(for views). But if you are planning to learn rails then I better recommend you to do it from scratch as you will have an idea of what is happening. You can see this tutorial which does most of the task through scratch.
Enjoy Rails!!

Modifying Rails: How do advanced users find out what needs to be changed?

I've been using Rails for a few months now, and I'm quite comfortable writing up a project & manipulating Rails to my needs, etc.
Recently I've been trying to get a little more advanced, so I've attempted to modify/add to the existing rails codebase: add new form helper methods, add a responds_to :pdf method, etc...and I've been having a lot of problems.
The difficulty is learning which code I need to modify; where that code is located, and how to ensure I don't miss related code in other files. I'm guessing there's a way people learn to do this, but at the moment I'm mostly just guessing-and-hoping.
I guess my question is, how do Rails folks go about learning where the code they need to modify is edited & the approach to editing it? It seems like it's just something you need to know from prior familiarity, but I'm guessing there has to be a simple method for understanding where (and what) to edit.
Any ideas appreciated...cheers
I highly recommend Jose Valim's Crafting Rails Applications
You go through advanced projects, building out the types of engines and customizations that will take you to the next level in your Rails development.
From the site:
This book will help you understand Rails 3’s inner workings, including
generators, template handlers, internationalization, routing, and
responders.
What you are asking for is how MVC works. Basicly you can say:
1.) Put logic to the model! The model is the pivot everything turns around.
2.) The Controller is a middleman between the model and the view. You dont put any logic here that isnt related to selecting data from the database that should be displayed in the view. If you use one selection logic more than once create a scope in the Model and use it in the Controller.
3.) The View is only there to display things! You dont put any logic here! All the logic comes from the model and the data comes from the controller. The only logic your using here are loops through arrays of data that should be displayed.
Then you have some things missing. If you have a task that is related to an external service like lets say a SOAP Service you write a class for that too! Just whithout using ActiveRecord::Base inheritance like its generated by the scaffolder. You can call this Class in other models. Dont put this to the controller or copy the code in every class that needs it! Stay DRY (Dont Repeat Yourself). Just write a class for it and include it in the other models!
Another thing thats a Database basic: Dont store data that could be calculated from other fields from the database! You can add methods that calculate the stuff you need but dont start with duplicates.

Ruby on Rails - Best practice / method for loading side column content/blocks

I am developing a community / news article website where there is a side column with different "blocks" on nearly all pages. In these blocks is "Recent Articles (showing five most recent articles)," "Recent Blogs," "Recent Comments," you get the drift.
When I started out building the application, I wasn't real sure where to put the controller code (say, to call #recent_articles = Article.where...etc). I didn't think it could go into the Articles controller, because it's not always the Articles controller being called. So I thought it would work best in the application controller, as most content on the site would be calling this. I put "#recent_content" into the application controller, did a :before_filter to load it.
You might see the flaw in this. As I'm getting better with Rails, I went back to refactor as the site was loading horribly and sure enough, all my logic in the application controller defined by before_filter was being loaded on every action, no matter if it was needed or not. (The site sped up dramatically when I cleaned house on the application controller).
My mistake is realized, but I still need to define the instance variables for #recent_articles, #recent_blogs, etc somewhere, so they load up only when needed. Granted I'll be eventually caching the site content when it goes into production, but I want to be a good Rails programmer here.
So here is my question...exactly how would you handle this situation and where would you put the logic? I can think of two ways, not sure which one is better...
The first way...I took a look at a project from another Rails developer and I noticed he was doing odd things like this by creating files in the /lib folder. For example, defining a method for page meta tags or active menu states. I honestly haven't messed with the /lib folder before, figuring most of my stuff should stay in the /app folder.
The second way...seems to me like helpers might seem the way to go. Maybe I could define a "recent_articles" helper, call my #recent_articles instance variable in there, then render and pass the results to a view file in my shared folder.
Overall, which one of these ways is the better way to go, either from a performance or best-practices viewpoint? Or is there a better way of doing this that I'm unaware of?
Whenever there are many models that can call a particular method, i would probably use a module. I think that is what you are talking about in your first idea, since /lib is where modules are placed.
You can use helpers as well, but it's a good idea to keep logic out of helpers, only in models if possible. Helpers should be just used as a way to present data, they are part of views. If logic is added, then something is wrong :)
Make sure that you do not have logic in your controllers as well. I would be doing the same things in the beginning, but it's really a bad idea. Instead, put everything in your models, or maybe a module if they seem to be used by many other models.
Hope that helps you a bit :)

Ruby on Rails simple website layout

I'm learning RoR, I've read some tutorials (railstutorial for the first one),
but I've a problem to define the logic layout of the my first simple website.
The structure is:
When you go to mysite.com you see a welcome page with the signup form or the link for login.
If you signup or you login into the site, you are at mysite.com/dashboard and you see a list of your messages.
You can go to mysite.com/$username and you see a page with a form where you can write a message for the $username.
Stop. That's it. It's very simple, I know, but is for learning.
The problem is this: I'm new to MVC paradigm and I don't know how structure the logic layout of my app. Of course there'll two models: User and Message. But for controllers? And which functions in any controllers? Should I use scaffolding?
Please give me a help, I'm very confused.
Thank you.
Controllers are the logic for the data, so to login/sign-up is really validating/creating a user, if you need to view the users dash board, well that's a look up on the user data so he goes there as well.
The messages, that will be a separate controller that can create/view messages!
As others have pointed out, your controllers contain the logic for your code and invoke views based on that logic by rendering or redirecting to pages. You can define whatever actions you want in your controllers, and then use routes to map a particular URL to a controller action. That being said, Rails gets a lot easier if you "go with the flow" and make some simple assumptions about the actions that could happen. Both your users and your messages represent rows in their respective database tables. There's no much you can do to a row in a database table - you can Create it, Read it, Update it, or Delete it (CRUD). If you define your actions in terms of these four logical actions, Rails lets you generate some easy routes.
You can back into any URL schema that you want, but what you are describing is:
Read the messages that are for a user on the dashboard
Create a message for a user when you go to another page (mysite/username)
Each of these maps to a CRUD action that you should be defining in your controllers.
Agreed also with other advice to simply do a few more tutorials that will probably clear this up.
If you haven't already, read Getting Started with Rails. Look out for the discussion on MVC and scaffolding. Playing around with scaffolding can help you learn where things go and is a great place to start for beginners.
Also, I highly recommend this book: Agile Web Development with Rails. It is very hands on and an easy read.

Resources