Coding and UX are Not the Same, Except When They Are

Web development is not just about development anymore. Gone are the days of plain black text on a plain white background (well, almost). The creation of great websites involves a lot more that just a code monkey working head down in a laptop at your local coffee shop. There are the web designers who come up with how a website should look, the UX designers who come up with how a site should act and feel, and the users who will either love it or hate it. The developer has to think about all of these stakeholders when writing code.

There is a reason why multiple disciplines have sprung up around the web: there is a need for multiple disciplines when creating for the web. Coders, historically, have become so deeply entrenched in making The Code work, that they can easily lose sight of the fact that a less technical, less experienced, or possibly drunk human being has to actually use the product they are coding. This "blinders" effect is so prevalent, that anyone who is not actively checking themselves for its symptons is probably suffering from it. UX designers force coders back into the real world, sometimes kicking and screaming. This shouldn't be the case, though. While code and UX are distinct areas of study with different techniques, they are more closely related than you might think. Consider the case of validating card numbers inputed into a payment form.

There are three mathematic tests to determine if a credit card number is valid. The first and second card number test only require the first few digits of the card number and the length:

| Card Type  | Begins With | Number Length | 
| :--------- | :---------- | :------------ | 
| AMEX       | 34 or 37    | 15            | 
| Discover   | 6011        | 16            | 
| MasterCard | 51-55       | 16            | 
| Visa       | 4           | 13 or 16      | 

The second test requires a quick arithmetic check to see if the sequence of digits is legit:

  1. Starting with the next to last digit and continuing with every other digit going back to the beginning of the card, double the digit.

  2. Sum all doubled and untouched digits in the number.

  3. If that total is a multiple of 10, the number is valid.

An example using a valid (albeit fake) card number:

Card #: 4408 0412 3456 7893

Step 1:  8 4 0 8 0 4 2 2 6 4 10 6 14 8 18 3

Step 2:  8+4+0+8+0+4+2+2+6+4+1+0+6+1+4+8+1+8+3 = 70

Step 3:  70 % 10 == 0  

How does this translate to code? Let's see what our first digits test looks like using some basic JavaScript:

var digits = the+input+card+numbers;  
if (digits.substring(0) == '4') {  
  return "This is a Visa";
} else if (digits.substring(0, 1) == '34' || digits.substring(0, 1) == '37') {
    return "This is an American Express";
} else if (digits.substring(0, 1) <= 55 && digits.substring(0, 1) >= 51) {
    return "This is a MasterCard";
} else if (digits.substring(0, 3) == '6011') {
    return "This is a Discover";
} else {
    return "This is not a valid card number.";
}

And the length test:

if (digits.length == 13 || digits.length == 15 || digits.length == 16) {  
   return "This is a valid length card number"
} else {
   return "Incorrect length, not a valid card number"
}

Finally, the number sequence test:

// Returns the reversed digits as an array
var reversed = digits.split('').reverse();

// Starting with second to last digit, double every other
for (var i = reversed.length - 2; i > 0; i -= 2) {  
    reversed[i] = reversed[i] * 2;
}

var sum = reversed.reduce(function (previousValue, currentValue) {  
    return previousValue + currentValue
}, 0)

if (sum % 10 == 0) {  
    return "This is a valid card number sequence"
} else {
    return "Not a valid sequence"
}

Let's look an example in the wild. Shopify's e-commerce storefronts use a clean design with a simple interface for credit card inputs:

I guess I'll just start typing my number...

...and the site does the rest.

This section implements the first digits test while the user is typing, confirming to the user that it is indeed paying attention. The number length test triggers when the cursor leaves the card number box, and the digit sequence test runs when the user goes to move on to the next step. Helpful, robust, and unobtrusive.

On the other hand, the online yo-yo retailer Yo-Yo USA is an example of a payment page that commits the dreaded Credit Card Type Dropdown sin.

What's wrong with this picture?

The first form handles, in two inputs, what the second form take four inputs to do. This is a non-trivial difference. By ignoring these opportunities to reduce the cognitive load for the user, a large application (like an e-commerce site) will become bloated, hard to navigate, and leave users (and their potential sales) behind. Again, if you are not actively checking for the symptoms, you've already succumb to the problem.

Your web application should follow the principles of Don't Make Me Think: The less brainpower the user has to put into the details, the more the user will get the big picture. Using a web application should not be a DIY roller-coaster journey of self-discovery. It should be painless and intuitive. A web application is a tool to make our lives easier using the power of the Internet. Remember to wield that power in the right way, even if you think that's someone else's job.

Will San Francisco Burn Again?

There is no doubt that San Francisco is an important city in today's technology economy. Giants like Google, Facebook, and Twitter, along with many other large companies are headquartered there. But in recent years, the tech community in San Francisco has been harshly criticized as an echo chamber and a primary driver of economic inequality.

How did we get here? Can examining the history of San Francisco shed any light on its current state? A leisurely stroll through the city's Wikipedia page reads like a modern-day TechCrunch article.

In the beginning:

The California Gold Rush brought a flood of treasure seekers ... prospectors accumulated in San Francisco... raising the population from 1,000 in 1848 to 25,000 by December 1849. The promise of fabulous riches was so strong that crews on arriving vessels deserted and rushed off to the gold fields, leaving behind a forest of masts in San Francisco harbor... Silver discoveries, including the Comstock Lode in 1859, further drove rapid population growth. With hordes of fortune seekers streaming through the city, lawlessness was common, and the Barbary Coast section of town gained notoriety as a haven for criminals, prostitution, and gambling.

The similarities to present times are uncanny. Simply replace "gold rush treasure seeker" with "Stanford dropout with an app idea" and the story reads exactly the same. The substitution works because their mindsets are the same: get rich quickly with as little effort as possible. At both points in time, an influx of treasure seekers drives explosive population growth. Disorder ensues. The city's infrastructure is ill-equipped to handle the increase, which leads to rampant crime and illicit behaviors.

The story continues:

Entrepreneurs sought to capitalize on the wealth generated by the Gold Rush. Early winners were the banking industry, with the founding of Wells Fargo in 1852 and the Bank of California in 1864... Catering to the needs and tastes of the growing population, Levi Strauss opened a dry goods business and Domingo Ghirardelli began manufacturing chocolate... In 1870, Asians made up 8% of the population... The city's sea of Victorian houses began to take shape, and civic leaders campaigned for a spacious public park, resulting in plans for Golden Gate Park. San Franciscans built schools, churches, theaters, and all the hallmarks of civic life... By 1890, San Francisco's population approached 300,000, making it the eighth-largest city in the U.S. at the time. Around 1901, San Francisco was a major city known for its flamboyant style, stately hotels, ostentatious mansions on Nob Hill, and a thriving arts scene.

Again, correlation abounds. The capitalists capitalize on the gold rush, profiting on the backs of aspiring gold seekers. Those coming in search of quick fortune are happy to accept the handouts freely waved about. No one bothers looking for a chair while the music plays so loudly.

Aren't we seeing exactly this situation, right now, in all of Silicon Valley? Pet industries catering to non-essential inconveniences as legitimate business models? Thankfully for denim and chocolate enthusiasts, Strauss and Ghirardelli made products that have lasted 150 years. Can the latest dating app purveyor say the same?

In true Buzzfeed clickbait tradition, what happened next will astound you:

At 5:12 am on April 18, 1906, a major earthquake struck San Francisco and northern California. As buildings collapsed from the shaking, ruptured gas lines ignited fires that spread across the city and burned out of control for several days. With water mains out of service, the Presidio Artillery Corps attempted to contain the inferno by dynamiting blocks of buildings to create firebreaks.[4] More than three-quarters of the city lay in ruins, including almost all of the downtown core.[2] Contemporary accounts reported that 498 people lost their lives, though modern estimates put the number in the several thousands.[4] More than half of the city's population of 400,000 was left homeless.[4] Refugees settled temporarily in makeshift tent villages in Golden Gate Park, the Presidio, on the beaches, and elsewhere. Many fled permanently to the East Bay.

*Emphasis added.

By many accounts, the 1906 San Fransciso earthquake was an unmitigated disaster, leveling nearly the entire city. First-responders had to blow up several buildings in an attempt to contain the gas-fed fires. Had the Richter scale existed, studies have estimated that the earthquake would've measured an 8.3 magnitude.

So how did an industrious city like San Francisco recover? How else, but by following the ancient proverb of "Move fast and break things":

Rebuilding was rapid and performed on a grand scale. Rejecting calls to completely remake the street grid, San Franciscans opted for speed… The earthquake hastened development of western neighborhoods that survived the fire, including Pacific Heights, where many of the city's wealthy rebuilt their homes.[5] In turn, the destroyed mansions of Nob Hill became grand hotels.City Hall rose again in splendid Beaux Arts style, and the city celebrated its rebirth at the Panama-Pacific International Exposition in 1915.[5]

A nouveau riche populace seeks to pat themselves on the back in front of the world. What better way that with an ostentatious party, showing off the latest technologies of the time? The hardware may have changed, but the self-congradulatory echo chamber remain.

What can we learn here? Do we believe the treasure seekers? Or are they flying too close to the sun to realize their shortcomings? Perhaps they are right, and a new world is just around the corner. Perhaps they've simply gotten good at ignoring their melting wings. If history teaches us anything, it's that the essence of San Francisco is the never-ending obsession with finding gold, no matter how many times they get burned.

Micro-Buntu, Fun with Github, and How to Break You JavaScript

Microsoft Gives in to Collaborates with Canonical, Brings Ubuntu to Windows

As we saw at last year's Build conference, Microsoft has found a new emphasis on open source tooling for the Windows platform. This year, they announced a huge addition to Windows 10:

"The Bash shell is coming to Windows. Yes, the real Bash is coming to Windows,"

Dustin Kirkland, a strategy guy at Canonical, explains why this is a good thing for both Windows and Ubuntu fans alike:

Finally, I imagine some of you -- long time Windows and Ubuntu users alike -- are still wondering, perhaps, "Why?!?" Having dedicated most of the past two decades of my career to free and open source software, this is an almost surreal endorsement by Microsoft on the importance of open source to developers. Indeed, what a fantastic opportunity to bridge the world of free and open source technology directly into any Windows 10 desktop on the planet. And what a wonderful vector into learning and using more Ubuntu and Linux in public clouds like Azure. From Microsoft's perspective, a variety of surveys and user studies have pointed to bash and Linux tools -- very specifically, Ubuntu -- be available in Windows, and without resource-heavy full virtualization.

Windows developers are sure to be excited about finally getting a legitimate command line interface. Workarounds and hacks have existed for a while, but have still lagged behind readily available Unix alternatives. Linux fans haven't responded as favorably, as evidenced by their choices of defeatist April Fools jokes.

As big a change as this announcement is, I see many developers being indifferent. Is a Bash shell really the tipping point for adoption of Windows as a serious development platform? Is adding features to Windows even the right approach to getting developers to use Microsoft products? The open-sourcing of .NET and introduction of Visual Studio Code were more effective at getting traction only because I could use them on my non-Windows platform. These platform just so happen to already have a Bash shell. We'll see how Satya handles this one down the line.

Simple Github Searches Give Glimpse into the Minds of Overworked Developers.

Bored at work developer looking for a quick laugh? Tired of the r/programmerhumor subreddit? Head on over to Github and try a few code searches.

Some other fun searches include:

  • "remove in production" (4,326,300 results)
  • "fix this later" (22,398,600 results)
  • "who wrote this" (4,477,677 results)

A related site in the same vein is Commit Logs from Last Night.

Recent Tiff Surrounding npm Has Developers Questioning Everything

It's a classic story, really. Guy writes code. Guy gets cease and desist from lawyers about the name of said code. Guy ignores. Lawyers send same letter to the one place that houses all of guy's code for others to use. Place concedes, removes one piece of guy's code. Guy gets mad and removes all of his other pieces of code, which just so happened to include a piece of code that is relied upon by some big name frameworks. Non-tech business trades claim that guy "broke the internet."

The problem here is that the backlash was towards npm. How dare they take action against a guy who was clearly breaking their rules, did not have a legal leg to stand on, and reacted childishly to the whole thing? Bring out the pitchforks!

It wasn't until Haney wrote this blog post that we got some sanity.

I get the impression that the NPM ecosystem participants have created a fetish for micro-packages. Rather than write any functions or code, it seems that they prefer to depend on something that someone else has written. It feels to me as if the entire job of an NPM-participating developer is writing the smallest amount of code possible to string existing library calls together in order to create something new that functions uniquely for their personal or business need.

Typical JavaScript developer's FizzBuzz solution.

The above image is sadly hilarious, because npm diehards will swear that modules are the best and only way to write code, even though, in some languages, FizzBuzz can be written in as little as SIX lines.

To Haney's credit, he makes a point that is impossible to argue against:

Second, even if the package’s logic is correct, I can’t help but be amazed by the fact that developers are taking on dependencies for single line functions that they should be able to write with their eyes closed. In my opinion, if you cannot write a left-pad, is-positive-integer, or isArray function in 5 minutes flat (including the time you spend Googling), then you don’t actually know how to code. Hell, any of these would make a great code screening interview question to determine whether or not a candidate can code.

The lesson here is that if you are a developer who is upset by a dependency change breaking your code, maybe a solution is to not rely on fragile dependencies.

3 Awesome Microsoft Things from Build 2015

This year’s Microsoft’s Build conference seems to mark the culmination of a giant turning point for the company. While it would be easy to credit the momentum of a new CEO for all of the company’s changes, the transition from plodding behemoth feeding on expensive proprietary systems to open-source community enthusiast is both stark and amazing.

whale

A historical photograph of Microsoft, circa 1998

Visual (Su Su) Studio Code

Tools are essential to a developer’s workflow. An informal survey of web developers I’ve met shows most using Webstorm, Sublime Text, or (for the purists) vim as a text editor. Macbooks are most common, with a few Thinkpads and Dells running Ubuntu thrown in.

None of these are Microsoft technologies.

Until Build 2015, Microsoft insisted that Visual Studio be limited to Windows operating systems only. Anyone who’s had to write code in a Windows environment knows that the lack of a good terminal and low adoption from the open-source community mean pain for developers. It seems like Microsoft has seen the writing on the wall, and decided to release one of their best tools as open-source software.

vscode

Ubuntu, meet Microsoft

Visual Studio Code brings two awesome features to the crowded IDE/code editor landscape: Intellisense and cross-platform compatibility. Intellisense is a context-aware code completion tool. It is a combination of code snippets, syntax guides, and autocomplete that detects what language you are in and presents appropriate options. Hard to explain, so check out this video to see how Intellisense can help you code faster.

As awesome as Intellisense is, the bigger story may be the fact that VSCode is being released across Mac and Linux operating systems. Developers like to try out shiny new toys, so eliminating barriers of entry should lead to increased adoption of Microsoft products. Combined with the open source releast of .NET, Microsoft is definitely on the right track to get their software in as many hands as possible

Windows 10 Universality-ness

The next item isn’t just one item, but more of an overall theme. Microsoft has clearly focused on creating a more universal platform with Windows 10.

Starting with the Windows phone platform, Microsoft showed off two technologies that integrate the desktop and mobile experience: Continuum and “universal” Windows 10 apps. Continuum allows a Windows phone to connect to a Windows 10 desktop via HDMI, and run any mobile apps natively on the desktop. These changes erase the line between what is a “mobile” app versus a “desktop” app on a Windows platform, a feat neither Apple nor Google have yet to accomplish.

Speaking of the competition, Microsoft have not forgotten about their southern rivals. The company reported that developers will be able to port their Android and iOS apps easily to Windows 10. How do they accomplish this incredible feat?

Windows Phones will include a Android subsystem that can run the majority of existing code from an Android app. Developers can use Windows APIs along with their existing code to get live tiles and other features working.

While most iOS developers won't bother with porting their apps to Windows 10, Android support is intriguing due to Microsoft's recent investment in CyanogenMod. Could Microsoft be gearing up to reincarnate the Windows Phone platform with a full-blown Android replacement OS based on CyanogenMod? The bigger question might be, would you buy one?

how-old.net destroys the Interwebs

albert<em>how</em>old

Not even close, I swear

Much like how Tim Cook called Dr. Dre from an on-stage laptop, Microsoft wasn’t afraid to show a lighter side to their products at their conference. As part of the day 2 keynote, Microsoft announced how-old.net, an advanced image processing algorithm disguised as a social-media distraction. How-old.net guesses the age and gender of any photo uploaded to the site. The hit-or-miss nature of the guesses were perfect fodder for social media networks craving maximum meme virality. Microsoft quietly accompanied the site with a comprehensive blog post on the tech ( a combination of machine learning APIs, Azure, and real-time analytics), while others on the internet found important uses for the site.

What does it all mean?

Does this mean that if the entire world isn’t using a Windows 10 laptop hooked in a Windows Phone hooked into a Hololens that Build 2015 is a complete failure? No. What these announcements do mean is a sea change in the software industry. If a giant like Microsoft can see the light of open source, and pivot so fully and wholeheartedly in a short span of time, what is stopping anyone else?

The State of JavaScript Frameworks

If there is something you want to build on the web, there is a JavaScript framework to do it. Want to emulate a RESTful Rails backend using Node instead? Sails is for you. Build mobile apps with React components? Get some Reapp in your life. Need an impossibly lightweight and fast client-side MVC? Mithril will be your one and only.

JavaScript will even fix your crappy 'scroll to top' button.

The current state of JavaScript framework development.

The problem with JavaScript ubiquity in web development is mistaking change for progress. Whenever a new framework is released, there tends to be a bit of of an “emperor’s new clothes” effect. While it's easy to bag on every newest flavor of the week. there are JavaScript frameworks that have proven useful for longer that the attention span of a teenager, and are being used to build some awesome stuff. Today we take a look at three: Angular, Meteor, and React.

The Stalwart: Angular

Out of the three listed, Angular is probably the most commonly used JavaScript framework. With backing from the Mountain View Monster themselves (Google), Angular is used by several high-traffic applications, such as MSNBC, Vevo, and Honest Company's e-commerce site. Angular plays nicely with open source back ends like Rails and Node, as well as proprietary solutions like .NET and ASP.NET.

Angular's biggest trick is adding dynamic functionality to otherwise static HTML markup. It accomplishes this feat with two-way data binding, which marries changes to either the view or the model to each other. When an Angular view is updated, the information is also changed, or "binded" to its model. When a model's data is changed, the view is updated automatically. This binding eliminates many of the errors that come from trying to write code to manipulate the DOM on data changes.

Being one of the most widely adopted frameworks also means that the resources for learning Angular are prevalent. CodeSchool has a fantastic video series that breaks down the components very well. Codecademy has also jumped into the fray with their own step by step exercises for tackling Angular.

The Challenger: Meteor

Meteor is unique on the this list as the only truly full stack framework. Unlike our other two contestants for Ruler of All JavaScript, Meteor is not maintained by a Bay-area behemoth, but rather the VC-backed collective of scrappy former MIT students known as Meteor Development Group. Meteor is starting to be adopted by several startups, most notably are Workpop, an Los Angeles-based jobs board for hourly workers, and Classcraft, a teaching gamifcation application.

Meteor’s biggest trick is reactive development. The modern web requires UI’s on the client to respond immediately to changes in data, without having to wait for server calls on every single action. Meteor accomplishes this feat by incorporating a TON of awesome tools that are unlike most other web development frameworks around. The combination of in-house developed tools like Blaze, Tracker, and DDP, combined with awesome existing technologies like Node, MongoDB, jQuery, and Handlebars makes for a comprehensive stack for building reactive web applications quickly.

For context, try to build a real-time chat application in Rails. Don’t worry, I’ll wait.

...

...

...

Back? Not a fun experience, huh? Exactly why Meteor is so awesome. If you need more proof, here’s the Internet’s take on Meteor and its place in modern web development:

Meteor has developed a robust community with great resources in a short time. Atmosphere a catalogue of Meteor packages, similar to Ruby gems. Crater is a Reddit/Hacker News-like community for Meteor news and happenings. There are several great podcasts as well, including The Meteor Podcast, MeteorClub, and Meteor Interviews.

The Phenom: React

Not to be outdone by Google, the Zuckerberg Gang have recently released React, a “JavaScript library for building user interfaces.” React is possibly the best solution yet to creating and using customized UI components. Justin Deal from Zapier Engineering explains it best:

With React, just like with a game engine, you simply specify how a given application state gets translated to a given view. If something changes, you don't change the view. Instead, you just render again and get a new view.

React adoption has been swift, and is currently utilized by two of the biggest web applications in the world: Facebook and Instagram. Some heavy duty credentials, indeed.

It's ironic that, while Angular puts the power of JavaScript directly into your HTML markup, React's new JSX syntax allows HTML to be customized and written directly in JavaScript. So, instead of writing a bunch of string soup to reference your HTML tags like this:

var Hello = React.createClass({displayName: 'Hello',  
    render: function() {
        return React.createElement("div", null, "Hello ", this.props.name);
    }
});

the JSX syntax allows a much more direct reference, like so:

var Hello = React.createClass({  
      render: function() {        
           return <div>Hello {this.props.name}</div>;      
  }    
});

As a web developer, I’ve always found the JavaScript/jQuery of doing HTML references a bit clunky and easy to screw up. The JSX syntax makes it easier to manipulate your views with all of the power of JavaScript in the browser. Add the highly reactive and realtime nature of React views, and you’ve got yourself an awesome new framework that promises to make web development easier.

The Winner: JavaScript Developers

So who is the winner of our JavaScript deathmatch? All three of these frameworks have pros and cons. I’ve always thought that part of our roles as developers is deciding which tool is right for the job. For comparison, here's a discussion among some React and Angular maintainers talking about various topics.

With multiple good tools available, our roles becomes both more involved and easier. Have a giant, constantly changing database that needs to be reflected in your front-end at scale? Angular is your best bet. Need to build an reactive prototype quickly and make your developers happy and more productive? Meteor fills your needs. Need modern view layers that are real-time an use fully customizable components? React is the one for you. You really can’t go wrong with any of these frameworks. In these three cases, the emperor’s new clothes are, in fact, as fancy as they appear to be.

Anatomy of a Rails Application, Part II: Controllers

As we learned previously, Rails uses views to show back-end data to a user. How does a Rails application know what data to show? When is an index view rendered rather than a show view? How does Rails control all of this stuff? You guessed it, with controllers. Today we'll go over how a Rails application makes data and actions available to these views using controllers.

This post is the second in a multi-part series on building a Rails application. Check out part 1 here.

Let's look at how PowerUp uses controllers.

Here are some additional resources: CodeSchool's Rails tutorial series has a lesson dedicated to controllers. RailsGuides are typically my first stop for Rails questions, and they have an excellent section on how routes and controllers interact.

Organizing Rails apps with RESTful controllers

Because Rails is designed as a web application framework, setting up our application's actions is centered around using HTTP verbs (GET, PUT/PATCH, POST, DELETE) to keep our code organized. Rails conventions give us a way to accomplish our typical database actions (create, read, update, destroy, or CRUD) using HTTP verbs. Further down the line, our views and paths will also be organized around these actions. Here's a list of the actions using users as an example:

  • index method returns a list of all of the users. HTTP verb: GET.
  • show returns a specific user. Can be used to retrieve a user's info. HTTP verb: GET.
  • new returns a form for creating a new user. Is related to the create action. HTTP verb: GET.
  • create creates a new user by adding its record to the database. HTTP verb POST.
  • edit returns a form for changing a user's info in the database. Is related to the update action. HTTP verb: GET.
  • update changes a user's record in the database. HTTP verb: PUT/PATCH.
  • destroy deletes a user's record in the database. HTTP verb; DELETE.

Next, let's generate a controller and start writing some Ruby code.

Generating the Controller in Rails

A Rails application makes it easy to generate controllers quickly. To do so, go to your terminal and first make sure you are in your application's directory (this gets me every time). Next, enter the following command:

rails generate controller users index

Let's break this command down to see what's happening. We are telling Rails to create a controller (not a model, which is the other option), to name it users, and to create an action in the controller called index as a Ruby method. While Rails can create these actions for us, we will always have the option of writing additional Ruby methods in any controller we generate.

We should now have two new files in our Rails app; app/controllers/users_controller.rb and app/views/index.html.erb. The ERB view file should be familiar from our previous look at Rails views. If we open the users_controller.rb, it should look like this:

class UsersController < ApplicationController  
  def index

  end
end  

This file is now our blank slate. From the controller, a Rails developer directs how information in the application is stored and rendered, and can direct how a user navigates the application.

Let's look at how some of the actions we previously defined would be implemented in our users controller. Here's the index action:

def index  
  @users = User.all
end  

The index defines the instance variable @users so that we may access this list of all users later on in the application, typically in the index.html.erb view. This is the most basic RESTful controller action, but wouldn't it be nice if we could create a new user as well? How would we write that action so it handles the database create AND the rendering of a specific path? With a little Ruby knowledge and a some Rails magic, we can write all of this in one method. Let's take a look:

def create  
  @user = User.new(user_params)  
  if @user.save    
    redirect_to user_path(@user), :notice => "Thanks for signing up! Here's your profile page."  
  else    
    render :new  
  end
end  

What's going on here? The create method is handling a few things for us:

  • Defining @user as a new user.
  • Checking if an attempt to save the user record is succssful. If it is, taking the user to the user show view (a "user profile"), and showing a confirm notice
  • If the attempt fails, redirecting back to the user new form.

The Rails magic in this method comes from the helpers like redirect_to, user_path, and render. The redirect_to helper does exactly what it says: redirects the user to a specific view. The user_pathis particular to the user show view, but you'll see that all of your application's view have some sort of _path helper assigned to it. Enter rake routes in your terminal to see a list of all of the available view paths. The render helper is another way to point to a particular view.

alt

A successful new user signup using the create method.

While we've gone over two of the RESTful actions in a Rails controller, they are others to consider when building your Rails application. Try writing the controller methods for some of the actions and see what you come up with. A typical Rails app will have at least one resource that has "full CRUD," or uses all of the controller actions. We'll explore Rails models and how they fit in with our controllers and views in the next installment.