sneha cynix

1593593835

Intermediate Rails: Understanding Models, Views and Controllers

This isn’t quite an intro to MVC, it’s a list of gotchas as you plod through MVC the first few times.

Here’s the big picture as I understand it:
The web server (mongrel, WEBrick, etc.) receives the request. It uses routes to find out which controller to use: the default route pattern is “/controller/action/id” as defined in config/routes.rb. In our case, it’s the “video” controller, method “show”, with the id parameter set to “15″. The web server then uses the dispatcher to create a new controller, call the action and pass the parameters. ruby on rails course helps you to learn more skills and techniques from industrial experts.

Controllers do the work of parsing user requests, data submissions, cookies, sessions and the “browser stuff”. They’re the pointy-haired manager that orders employees around. The best controller is Dilbert-esque: It gives orders without knowing (or caring) how it gets done. In our case, the show method in the video controller knows it needs to lookup a video. It asks the model to get video 15, and will eventually display it to the user.

Models are Ruby classes. They talk to the database, store and validate data, perform the business logic and otherwise do the heavy lifting. They’re the chubby guy in the back room crunching the numbers. In this case, the model retrieves video 15 from the database.

Views are what the user sees: HTML, CSS, XML, Javascript, JSON. They’re the sales rep putting up flyers and collecting surveys, at the manager’s direction. Views are merely puppets reading what the controller gives them. They don’t know what happens in the back room. In our example, the controller gives video 15 to the “show” view. The show view generates the HTML: divs, tables, text, descriptions, footers, etc.

The controller returns the response body (HTML, XML, etc.) & metadata (caching headers, redirects) to the server. The server combines the raw data into a proper HTTP response and sends it to the user.

It’s more fun to imagine a story with “fat model, skinny controller” instead of a sterile “3-tiered architecture”. Models do the grunt work, views are the happy face, and controllers are the masterminds behind it all. ruby on rails certification training along with real time projects.

Many MVC discussions ignore the role of the web server. However, it’s important to mention how the controller magically gets created and passed user information. The web server is the invisible gateway, shuttling data back and forth: users never interact with the controller directly.

SuperModels
Models are fat in Railsville: they do the heavy lifting so the controller stays lean, mean, and ignorant of the details. Here’s a few model tips:

Using ActiveRecord

class User < ActiveRecord::Base
end
The code < ActiveRecord::Base means your lowly User model inherits from class ActiveRecord::Base, and gets Rails magic to query and save to a database.

Ruby can also handle “undefined” methods with ease. ActiveRecord allows methods like “find_by_login”, which don’t actually exist. When you call “find_by_login”, Rails handles the “undefined method” call and searches for the “login” field. Assuming the field is in your database, the model will do a query based on the “login” field. There’s no configuration glue required.

Class and instance methods can cause confusion.

user (lowercase u) is an object, and you call instance methods like user.save.

User (capital U) is a class method – you don’t need an object to call it (like User.find). ActiveRecord adds both instance and class methods to your model.

As a tip, define class methods like User.find_latest rather than explicitly passing search conditions to User.find (thin controllers are better).

Using Attributes

Regular Ruby objects can define attributes like this:

attribute in regular Ruby

attr_accessor :name # like @name
def name=(val) # custom setter method
@name = val.capitalize # clean it up before saving
end

def name # custom getter
"Dearest " + @name # make it nice
end
Here’s the deal:

attr_accessor :name creates get and set methods (name= and name) on your model. It’s like having a public instance variable @name.
Define method name=(val) to change how @name is saved (such as validating input).
Define method name to control how the variable is output (such as changing formatting).
In Rails, attributes can be confusing because of the database magic. Here’s the deal:

ActiveRecord grabs the database fields and throws them in an attributes array. It makes default getters and setters, but you need to call user.save to save them.
If you want to override the default getter and setter, use this:

ActiveRecord: override how we access field

def length=(minutes)
self[:length] = minutes * 60
end

def length
self[:length] / 60
end
ActiveRecord defines a “[]” method to access the raw attributes (wraps the write_attribute and read_attribute). This is how you change the raw data. You can’t redefine length using

def length # this is bad
length / 60
end
because it’s an infinite loop (and that’s no fun). So self[] it is. This was a particularly frustrating Rails headache of mine – when in doubt, use self[:field].

Never forget you’re using a database

Rails is clean. So clean, you forget you’re using a database. Don’t.

Save your models. If you make a change, save it. It’s very easy to forget this critical step. You can also use update_attributes(params) and pass a hash of key -> value pairs.

Reload your models after changes. Suppose a user has_many videos. You create a new video, point it at the right user, and call user.videos to get a list. Will it work?

Probably not. If you already queried for videos, user.videos may have stale data. You need to call user.reload to get a fresh query. Be careful — the model in memory acts like a cache that can get stale.

Making New Models

There’s two ways to create new objects:

joe = User.new( :name => “Sad Joe” ) # not saved
bob = User.create ( :name => “Happy Bob” ) # saved
User.new makes a new object, setting attributes with a hash. new does not save to the database: you must call user.save explicitly. Method save can fail if the model is not valid.
User.create makes a new model and saves it to the database. Validation can fail; user.errors is a hash of the fields with errors and the detailed message.
Notice how the hash is passed. With Ruby’s brace magic, {} is not explicitly needed so

user = User.new( :name => “kalid”, :site => “instacalc.com” )
becomes

User.new( {:name => “kalid”, :site => “instacalc.com”} )
The arrow (=>) implies that a hash is being passed.

Using Associations

Quick quiz, hotshot: suppose users have a “status”: active, inactive, pensive, etc. What’s the right association?

class User < ActiveRecord::Base
belongs_to :status # this?
has_one :status # or this?
end
Hrm. Most likely, you want belongs_to :status. Yeah, it sounds weird. Don’t think about the phrase “has_one” and “belongs_to”, consider the meaning:

belongs_to: links_to another table. Each user references (links to) a status.
has_one: linked_from another table. A status is linked_from a user. In fact, statuses don’t even know about users – there’s no mention of a “user” in the statuses table at all. Inside class Status we’d write has_many :users (has_one and has_many are the same thing – has_one only returns 1 object that links_to this one).
A mnemonic:

“belongs_to” rhymes with “links_to”
“has_one” rhymes with “linked_from”
Well, they sort of rhyme. Work with me here, I’m trying to help.

These associations actually define methods used to lookup items of the other class. For example, “user belongs_to status” means that user.status queries the Status for the proper status_id. Also, “status has_many :users” means that status.users queries the user table for everyone with the current status_id. ActiveRecord handles the magic once we declare the relationship.

Using Custom Associations

Suppose I need two statuses, primary and secondary? Use this:

belongs_to :primary_status, :model => ‘Status’, :foreign_key => ‘primary_status_id’
belongs_to :secondary_status, :model => ‘Status’, :foreign_key => ‘secondary_status_id’
You define a new field, and explicitly reference the model and foreign key to use for lookups. For example, user.primary_status returns a Status object with the id of “primary_status_id”. Very nice.

Quick Controllers
This section is short, because controllers shouldn’t do much besides boss the model and view around. They typically:

Are hard to debug. Use render :text => “Error found” and return to do printf-style debugging in your page. This is another good reason to put code in models, which are easy to debug from the console.
Use sessions to store data between requests: session[:variable] = “data”.
I’ll say it again because it’s burned me before: use @foo (not “foo”) to pass data to the view.

Using Views
Views are straightforward. The basics:

Controller actions use views with the same name (method show loads show.rhtml by default)
Controller instance variables (@foo) are available in all views and partials (wow!)
Run code in a view using ERB:

<% … %>: Run the code, but don’t print anything. Used for if/then/else/end and array.each loops. You can comment out sections of HTML using <% if false %> Hi there <% end %>. You get a free blank line, since you probably have a newline after the closing %>.

<%- … %>: Run the code, and don’t print the trailing newline. Use this when generating XML or JSON when breaking up .rhtml code blocks for your readability, but don’t want newlines in the output.

<%= … %>: Run the code and print the return value, for example: <%= @foo %> (You did remember the @ sign for controller variables passed to the view, right?). Don’t put if statements inside the <%=, you’ll get an error.

<%= h … %>: Print the code and html escape the output: > becomes >. h() is actually a Ruby function, but called without parens, as Rubyists are apt to do.

It’s a bit confusing when you start out — run some experiments in a dummy view page.

The MVC pattern is a lot to digest in one sitting. As you become familiar with it, any Rails program becomes easy to dissect: it’s clear how the pieces fit together. MVC keeps your code nice and modular, great for debugging and maintenance.

If you want to Gain In-depth Knowledge on Ruby on rails, please go through this link ruby on rails online training

#rails training #ruby certification #rails online course #ruby on rails online #ruby training

What is GEEK

Buddha Community

Intermediate Rails: Understanding Models, Views and Controllers

sneha cynix

1593593835

Intermediate Rails: Understanding Models, Views and Controllers

This isn’t quite an intro to MVC, it’s a list of gotchas as you plod through MVC the first few times.

Here’s the big picture as I understand it:
The web server (mongrel, WEBrick, etc.) receives the request. It uses routes to find out which controller to use: the default route pattern is “/controller/action/id” as defined in config/routes.rb. In our case, it’s the “video” controller, method “show”, with the id parameter set to “15″. The web server then uses the dispatcher to create a new controller, call the action and pass the parameters. ruby on rails course helps you to learn more skills and techniques from industrial experts.

Controllers do the work of parsing user requests, data submissions, cookies, sessions and the “browser stuff”. They’re the pointy-haired manager that orders employees around. The best controller is Dilbert-esque: It gives orders without knowing (or caring) how it gets done. In our case, the show method in the video controller knows it needs to lookup a video. It asks the model to get video 15, and will eventually display it to the user.

Models are Ruby classes. They talk to the database, store and validate data, perform the business logic and otherwise do the heavy lifting. They’re the chubby guy in the back room crunching the numbers. In this case, the model retrieves video 15 from the database.

Views are what the user sees: HTML, CSS, XML, Javascript, JSON. They’re the sales rep putting up flyers and collecting surveys, at the manager’s direction. Views are merely puppets reading what the controller gives them. They don’t know what happens in the back room. In our example, the controller gives video 15 to the “show” view. The show view generates the HTML: divs, tables, text, descriptions, footers, etc.

The controller returns the response body (HTML, XML, etc.) & metadata (caching headers, redirects) to the server. The server combines the raw data into a proper HTTP response and sends it to the user.

It’s more fun to imagine a story with “fat model, skinny controller” instead of a sterile “3-tiered architecture”. Models do the grunt work, views are the happy face, and controllers are the masterminds behind it all. ruby on rails certification training along with real time projects.

Many MVC discussions ignore the role of the web server. However, it’s important to mention how the controller magically gets created and passed user information. The web server is the invisible gateway, shuttling data back and forth: users never interact with the controller directly.

SuperModels
Models are fat in Railsville: they do the heavy lifting so the controller stays lean, mean, and ignorant of the details. Here’s a few model tips:

Using ActiveRecord

class User < ActiveRecord::Base
end
The code < ActiveRecord::Base means your lowly User model inherits from class ActiveRecord::Base, and gets Rails magic to query and save to a database.

Ruby can also handle “undefined” methods with ease. ActiveRecord allows methods like “find_by_login”, which don’t actually exist. When you call “find_by_login”, Rails handles the “undefined method” call and searches for the “login” field. Assuming the field is in your database, the model will do a query based on the “login” field. There’s no configuration glue required.

Class and instance methods can cause confusion.

user (lowercase u) is an object, and you call instance methods like user.save.

User (capital U) is a class method – you don’t need an object to call it (like User.find). ActiveRecord adds both instance and class methods to your model.

As a tip, define class methods like User.find_latest rather than explicitly passing search conditions to User.find (thin controllers are better).

Using Attributes

Regular Ruby objects can define attributes like this:

attribute in regular Ruby

attr_accessor :name # like @name
def name=(val) # custom setter method
@name = val.capitalize # clean it up before saving
end

def name # custom getter
"Dearest " + @name # make it nice
end
Here’s the deal:

attr_accessor :name creates get and set methods (name= and name) on your model. It’s like having a public instance variable @name.
Define method name=(val) to change how @name is saved (such as validating input).
Define method name to control how the variable is output (such as changing formatting).
In Rails, attributes can be confusing because of the database magic. Here’s the deal:

ActiveRecord grabs the database fields and throws them in an attributes array. It makes default getters and setters, but you need to call user.save to save them.
If you want to override the default getter and setter, use this:

ActiveRecord: override how we access field

def length=(minutes)
self[:length] = minutes * 60
end

def length
self[:length] / 60
end
ActiveRecord defines a “[]” method to access the raw attributes (wraps the write_attribute and read_attribute). This is how you change the raw data. You can’t redefine length using

def length # this is bad
length / 60
end
because it’s an infinite loop (and that’s no fun). So self[] it is. This was a particularly frustrating Rails headache of mine – when in doubt, use self[:field].

Never forget you’re using a database

Rails is clean. So clean, you forget you’re using a database. Don’t.

Save your models. If you make a change, save it. It’s very easy to forget this critical step. You can also use update_attributes(params) and pass a hash of key -> value pairs.

Reload your models after changes. Suppose a user has_many videos. You create a new video, point it at the right user, and call user.videos to get a list. Will it work?

Probably not. If you already queried for videos, user.videos may have stale data. You need to call user.reload to get a fresh query. Be careful — the model in memory acts like a cache that can get stale.

Making New Models

There’s two ways to create new objects:

joe = User.new( :name => “Sad Joe” ) # not saved
bob = User.create ( :name => “Happy Bob” ) # saved
User.new makes a new object, setting attributes with a hash. new does not save to the database: you must call user.save explicitly. Method save can fail if the model is not valid.
User.create makes a new model and saves it to the database. Validation can fail; user.errors is a hash of the fields with errors and the detailed message.
Notice how the hash is passed. With Ruby’s brace magic, {} is not explicitly needed so

user = User.new( :name => “kalid”, :site => “instacalc.com” )
becomes

User.new( {:name => “kalid”, :site => “instacalc.com”} )
The arrow (=>) implies that a hash is being passed.

Using Associations

Quick quiz, hotshot: suppose users have a “status”: active, inactive, pensive, etc. What’s the right association?

class User < ActiveRecord::Base
belongs_to :status # this?
has_one :status # or this?
end
Hrm. Most likely, you want belongs_to :status. Yeah, it sounds weird. Don’t think about the phrase “has_one” and “belongs_to”, consider the meaning:

belongs_to: links_to another table. Each user references (links to) a status.
has_one: linked_from another table. A status is linked_from a user. In fact, statuses don’t even know about users – there’s no mention of a “user” in the statuses table at all. Inside class Status we’d write has_many :users (has_one and has_many are the same thing – has_one only returns 1 object that links_to this one).
A mnemonic:

“belongs_to” rhymes with “links_to”
“has_one” rhymes with “linked_from”
Well, they sort of rhyme. Work with me here, I’m trying to help.

These associations actually define methods used to lookup items of the other class. For example, “user belongs_to status” means that user.status queries the Status for the proper status_id. Also, “status has_many :users” means that status.users queries the user table for everyone with the current status_id. ActiveRecord handles the magic once we declare the relationship.

Using Custom Associations

Suppose I need two statuses, primary and secondary? Use this:

belongs_to :primary_status, :model => ‘Status’, :foreign_key => ‘primary_status_id’
belongs_to :secondary_status, :model => ‘Status’, :foreign_key => ‘secondary_status_id’
You define a new field, and explicitly reference the model and foreign key to use for lookups. For example, user.primary_status returns a Status object with the id of “primary_status_id”. Very nice.

Quick Controllers
This section is short, because controllers shouldn’t do much besides boss the model and view around. They typically:

Are hard to debug. Use render :text => “Error found” and return to do printf-style debugging in your page. This is another good reason to put code in models, which are easy to debug from the console.
Use sessions to store data between requests: session[:variable] = “data”.
I’ll say it again because it’s burned me before: use @foo (not “foo”) to pass data to the view.

Using Views
Views are straightforward. The basics:

Controller actions use views with the same name (method show loads show.rhtml by default)
Controller instance variables (@foo) are available in all views and partials (wow!)
Run code in a view using ERB:

<% … %>: Run the code, but don’t print anything. Used for if/then/else/end and array.each loops. You can comment out sections of HTML using <% if false %> Hi there <% end %>. You get a free blank line, since you probably have a newline after the closing %>.

<%- … %>: Run the code, and don’t print the trailing newline. Use this when generating XML or JSON when breaking up .rhtml code blocks for your readability, but don’t want newlines in the output.

<%= … %>: Run the code and print the return value, for example: <%= @foo %> (You did remember the @ sign for controller variables passed to the view, right?). Don’t put if statements inside the <%=, you’ll get an error.

<%= h … %>: Print the code and html escape the output: > becomes >. h() is actually a Ruby function, but called without parens, as Rubyists are apt to do.

It’s a bit confusing when you start out — run some experiments in a dummy view page.

The MVC pattern is a lot to digest in one sitting. As you become familiar with it, any Rails program becomes easy to dissect: it’s clear how the pieces fit together. MVC keeps your code nice and modular, great for debugging and maintenance.

If you want to Gain In-depth Knowledge on Ruby on rails, please go through this link ruby on rails online training

#rails training #ruby certification #rails online course #ruby on rails online #ruby training

Hollie  Ratke

Hollie Ratke

1604142000

Converting Your First Ruby CLI App Into a Ruby on Rails Web App

I have a CLI app that I created in Ruby for my first project at Flatiron School. I’m pretty proud of what I accomplished in just a couple of days. The app was built from scratch with nothing but the basic knowledge of Ruby that I learned in a little over a week. The fact that the user interface was working in time for my presentation was a huge relief. I had something to show everyone, and it brought me back to my early days of programming in a dos prompt — where my interest in coding truly began.

Image for post

my first Ruby CLI app

As cute and nostalgic as my little app was, I knew I wanted to build on it someday. My goal was to give my users a more visual and interactive experience as they navigated through my text-based app. I had visions of adding more user stories, and some cool ASCII graphics with a background soundtrack of cheesy arcade music. To add more under the hood and additional flair would take a bit of time and attention — and time was not on my side while attending school. Vowing to come back to it, I put my project expansion on the back burner while Mod 2 of Flatiron got underway.

In Mod 2, I began to learn Ruby on Rails. Rails is a web application framework that is written in Ruby and provides the backend functionality of a database and a web server, as well as the front end functionality of creating web pages for the user experience. It took me some effort to understand Rails, as I clumsily tried to keep track of all the many moving parts. I at times literally felt like I was on a runaway freight train, just trying to grasp at all the information that was coming at me. Rails is actually a beast of a framework, and there is A LOT to learn. One thing that was helpful to think about is that there is a process to everything you do when you are building things in Rails. This makes it easier to break the entire process down step by step. It is also true that the more you do something, the better you get at it. I learned a great deal by making mistakes and learning how to fix them.

The brilliance of Rails is that you can see your mistakes happening directly in the web browser as you code. Having an artistic and creative background, I need to see things and to learn by doing. Rails gives me both of those qualities. I also lack patience (I’m learning how to unlearn this), so the fact that there’s just so much you can do in such a short amount of time, when creating a basic web app, is a form of instant gratification for me. I can see what I’m building in real time, which gets me super excited to build things!

#web-app-development #ruby-on-rails #rails #ruby-on-rails-development #model-view-controller

Ruby on Rails Development Services | Ruby on Rails Development

Ruby on Rails is a development tool that offers Web & Mobile App Developers a structure for all the codes they write resulting in time-saving with all the common repetitive tasks during the development stage.

Want to build a Website or Mobile App with Ruby on Rails Framework

Connect with WebClues Infotech, the top Web & Mobile App development company that has served more than 600 clients worldwide. After serving them with our services WebClues Infotech is ready to serve you in fulfilling your Web & Mobile App Development Requirements.

Want to know more about development on the Ruby on Rails framework?

Visit: https://www.webcluesinfotech.com/ruby-on-rails-development/

Share your requirements https://www.webcluesinfotech.com/contact-us/

View Portfolio https://www.webcluesinfotech.com/portfolio/

#ruby on rails development services #ruby on rails development #ruby on rails web development company #ruby on rails development company #hire ruby on rails developer #hire ruby on rails developers

Bette  Shanahan

Bette Shanahan

1594329600

America’s Next Top Model View Controller

At the heart of web application creation is the MVC design pattern. MVC stands for Model, View, and Controller. Essentially, it is the accepted paradigm by which we model our applications. This pattern is used by many programming languages, like Python, JavaScript, C#, and my first (and only, so far) experience with it was through Ruby/Rails, which is what this article is based on!

Essentially, the Model, View, Controller model separates web-app design into three interconnected areas. Understanding the structure of MVC is essential to understanding the design patterns programmers use to build apps every day, and will help you immensely on your journey to building your own.

Personally, the best way that I learn information is by relating it to something I’m familiar with. By the title of this article I think you can guess what I’m about to do…

Image for post

Yes. America’s Next Top Model View Controller. I’m sorry in advance.

Take a look at this graphic as you follow along, and save this somewhere you can reference back:

Image for post

this graphic is based on Rails, but you can get a general sense of how it all works for any language that uses MVC.

We start with the browser. Information is requested from the server by the client. That’s you, our hopeful contestant! From there, that request is shown to the router. Let’s think of the router as the casting director, shall we? We loved your video and there’s a high chance you’ll bring the TV worthy drama. Depending on your request, the router will send it over to…

The Controller

Image for post

Like Tyra Banks, the Controller is the Boss of the show.

I think of the Controller as the mastermind of the MVC framework. So obviously, the Controller is the Tyra Banks of web-application design.

#web-app-development #programming #rails #model-view-controller #mvc

The history of Model-View-Presenter

With modern web applications taking care of more and more system concerns as time progresses, we find ourselves looking for battle-hardened, proven practices that have stood the test of time.

Does it even makes sense to speak of software architecture for the front-end or is it a pipe dream? It turns out that the challenge of maintaining a complex front-end is a problem that was identified at least as early as the 1970s.

Join me, as we dust off the history books and discover the origins of the Model-View-Presenter design pattern from a modern web perspective.

#angular #model-view-presenter #model-view-controller #frameworks #design-patterns #software-architecture #history