Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Frog Face
Nov 29, 2004
if im not better than God im the closest one

BonzoESC posted:

To keep out browsers, run the android app over https with http basic authentication and a hardcoded password. The https means that people will have to take five minutes to unzip and strings the apk to get your hardcoded password instead of thirty seconds to use wireshark.

Assuming the CRUD app is for your use only, just use a different http basic auth password and don't share it.

That seems decent enough, thanks.

Adbot
ADBOT LOVES YOU

Doc Hawkins
Jun 15, 2010

Dashing? But I'm not even moving!


Assuming I'm writing my own tasks, is there anything Rake can do that Thor can't?

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Oh man. I am having a hell of a time getting postgres running. It used to work fine... then I didn't use it for a while, now I'm getting the `server not listening error' ( OSX10.7 )
My pg_hba.conf and postgresql.conf check out fine.

Running `ps aux | grep postgres' shows that I DO have a server process running:
code:
$ ps aux | grep postgres
postgres       56925   0.0  0.0  2466492    844   ??  Ss    3:50PM   0:00.01 /sbin/launchd
root           56923   0.0  0.0  2469616   2096 s000  S     3:50PM   0:00.02 su - postgres
root           56922   0.0  0.1  2459500   2300 s000  S     3:50PM   0:00.03 sudo su - postgres
postgres       56976   0.0  0.0  2434892    444 s000  S+    3:53PM   0:00.00 grep postgres
postgres       56937   0.0  0.0  2468528   1212   ??  S     3:50PM   0:00.01 /usr/sbin/distnoted agent
postgres       56935   0.0  0.1  2489460   5624   ??  SN    3:50PM   0:00.07 
        /System/Library/Frameworks/CoreServices.framework/Frameworks/Metadata.framework/Versions/A/Support/mdworker 
        -s mdworker -c MDSImporterWorker -m com.apple.mdworker.pool.0
postgres       56927   0.0  0.0  2435492    988 s000  S     3:50PM   0:00.02 -bash
Any ideas? VERY open to suggestions, ha.

e, oh yeah, here's what ActiveRecord throws:
code:
could not connect to server: Connection refused
	Is the server running on host "localhost" (127.0.0.1) and accepting
	TCP/IP connections on port 5432?
could not connect to server: Connection refused
	Is the server running on host "localhost" (::1) and accepting
	TCP/IP connections on port 5432?
could not connect to server: Connection refused
	Is the server running on host "localhost" (fe80::1) and accepting
	TCP/IP connections on port 5432?
e2, pg_ctl start doesn't work either
code:
Alexs-MacBook-Air:bin postgres$ ./pg_ctl start
pg_ctl: no database directory specified and environment variable PGDATA unset
Try "pg_ctl --help" for more information.

A MIRACLE fucked around with this message at 22:10 on Jan 4, 2012

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

A MIRACLE posted:

Oh man. I am having a hell of a time getting postgres running. It used to work fine... then I didn't use it for a while, now I'm getting the `server not listening error' ( OSX10.7 )
My pg_hba.conf and postgresql.conf check out fine.

Where'd you install postgres from? Lion comes with a psql client that doesn't work with homebrew postgres, and it's pretty expedient to sudo rm /usr/bin/psql /usr/bin/createdb /usr/bin/dropdb

Also what's your database.yml? Mine works with homebrew postgres and looks like this:
code:
development:
  adapter: postgresql
  database: triskelion-dev
  pool: 5
  timeout: 5000

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

BonzoESC posted:

Where'd you install postgres from? Lion comes with a psql client that doesn't work with homebrew postgres, and it's pretty expedient to sudo rm /usr/bin/psql /usr/bin/createdb /usr/bin/dropdb

Also what's your database.yml? Mine works with homebrew postgres and looks like this:
code:
development:
  adapter: postgresql
  database: triskelion-dev
  pool: 5
  timeout: 5000


Pretty generic:
code:
development:
  adapter: postgresql 
  database: db/development
  username: postgres
  host: localhost
  pool: 5
  timeout: 5000
About to leave work, I'll check out your suggestion when I get back.
`Running' 9.1, used the installer from PG's website IIRC.

Pardot
Jul 25, 2001




I installed via brew, and have this in my env

$ env | grep pgda
PGDATA=/usr/local/var/postgres

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

A MIRACLE posted:

Pretty generic:
code:
development:
  adapter: postgresql 
  database: db/development
  username: postgres
  host: localhost
  pool: 5
  timeout: 5000
About to leave work, I'll check out your suggestion when I get back.
`Running' 9.1, used the installer from PG's website IIRC.

Yeah, it's probably not listening on a port by default and it doesn't silently reconfigure itself to use a local socket like mysql does. Just yank out the username and host stuff.

ZanderZ
Apr 7, 2011

by T. Mascis
I am the Saul Goodman of freelance Rails development...

After setting up an online chat box function.
There ya go, all set! The only thing holdin your customer service abilities back now are the shotty English skills of whichever 3rd world citizen employed by whatever company you've decided to outsource to! Don't let em get trolled too hard by some 13 year iPhone wielding snot, bored out of his mind in history class!

After setting up an online ticket submission system.
Welp, you're good! Good luck with the new online ticket submission system! God knows how anyone's gonna request help from the I.T department when the internets' down, but that's a whole other can of worms I'd rather not get into, cuz I'm off to cash your check, before you can say, "Wait, what?!"

After setting up a log in/out user registration database.
Ok, all set! Hope it makes you feel more exclusive! Sure registration is free and it doesn't actually grant the user more access to content, but they'll love the redundant spam emails with all the pretty colors, ammirite!? Now let's talk future! What's it your willing to pay me to set up the world's #1 most used analytics platform by Google, on your website!? Hell, if you want, I can bang out some javascript and tie a journey to the registration page so they don't even have to hit "submit" in order to get bombed with spam from your site!

Annnnnnnnnnd time! Alright, that app took three hours and twelve minutes. Better make it an even five hours!

(I wish I had the balls to say this poo poo to my clients)

Seriously though, Rails is awesome and I've pretty much recycled everything I've ever made from the first tutorial I did. I highly recommend this environment to anyone looking to learn how to develop. My only advice is to absorb as much information as you can without trying to bash it into your head. Don't get too bogged down in understanding the details, just write the code, finish your first app and then mess around with it by adding more features.

ZanderZ fucked around with this message at 16:42 on Jan 5, 2012

hmm yes
Dec 2, 2000
College Slice
... but make sure the first thing you do is learn TDD or BDD for Rails :negative:

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

atastypie posted:

... but make sure the first thing you do is learn TDD or BDD for Rails :negative:

A hundred times this. Being fast at writing unmaintainable crap is arguably worse than being slow at it.

Meat Street
Oct 17, 2004

knowin' nothin' in life but to be legit

atastypie posted:

... but make sure the first thing you do is learn TDD or BDD for Rails :negative:

In this vein, do you guys have opinions on PragProg's Cucumber and RSpec books? I'm learning BDD as I go at this job, and would love to have some solid canonical resources to refer to. Thoughts?

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Re: Postgres woes; cc: BonzoESC, Pardot

Well I'm an idiot and don't know how to read the output of ps, which led me to believe that postgres had an active server process (it didn't). Needless to say today has not been the most productive day as I am still struggling with launching the server.

So I do sudo su - postgres to run pg_ctl start, which tells me that I don't have PGDATA set as an env. variable. This is news to me as PG was running flawlessly a few weeks ago. But I digress, export PGDATA=/Library/Postgresql/9.1/data and continue. Then pg_ctl tells me that my data folder has too many permissions. More specifically
code:
FATAL:  data directory "/Library/PostgreSQL/9.1/data" has group or world access
DETAIL:  Permissions should be u=rwx (0700).
great. This is where I'm stuck. I ran chmod u=rwx /Library/PostgreSQL/9.1/data as both root and postgres to no avail, as in I still get the error. Any suggestions comments and or feedback are welcome. Thanks everybody.

manero
Jan 30, 2006

A MIRACLE posted:

code:
FATAL:  data directory "/Library/PostgreSQL/9.1/data" has group or world access
DETAIL:  Permissions should be u=rwx (0700).
great. This is where I'm stuck. I ran chmod u=rwx /Library/PostgreSQL/9.1/data as both root and postgres to no avail, as in I still get the error. Any suggestions comments and or feedback are welcome. Thanks everybody.

That only sets the user permissions, it still probably has group or world. Try "chmod 0700 /Library/PostgreSQL/9.1/data"

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug
Install postgres from homebrew, follow its instructions, call me in the morning.

FuncType
Mar 29, 2007

Tactical Wiener Lover
Just stopping by to say that I setup http://gitlabhq.com/ at work today for internal testing and holy poo poo this kicks asses. Huge props go out to the guys powering this.

It's just a fancy Rails app that essentially emulates github for internal networks. Not quite as solid as Github Enterprise but pretty great for free.

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

BonzoESC posted:

Install postgres from homebrew, follow its instructions, call me in the morning.

Just got to this. Thanks man I'm good to go now.

Doc Hawkins
Jun 15, 2010

Dashing? But I'm not even moving!


Is there some way to not need
code:
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__)) + '/../lib/')
at the top of my bin files? I see other projects that just start requiring stuff without this kind of hideous declaration, but I can't figure out how they're managing it.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Doc Hawkins posted:

Is there some way to not need
code:
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__)) + '/../lib/')
at the top of my bin files? I see other projects that just start requiring stuff without this kind of hideous declaration, but I can't figure out how they're managing it.

Thor's gemspec declares that it wants its lib added to the load path: https://github.com/wycats/thor/blob/master/thor.gemspec#L21

canned from the band
Sep 13, 2007

I'm a man of intensity. Of cool, and youth, and passionately

Meat Street posted:

In this vein, do you guys have opinions on PragProg's Cucumber and RSpec books? I'm learning BDD as I go at this job, and would love to have some solid canonical resources to refer to. Thoughts?

Haven't read the Cucumber book, but the RSpec book is one of the best programming books I've read in a long time. TBH it shouldn't even be called the RSpec book, it's basically a complete walkthrough for BDD and covers a load of Cucumber.

Doc Hawkins
Jun 15, 2010

Dashing? But I'm not even moving!


BonzoESC posted:

Thor's gemspec declares that it wants its lib added to the load path: https://github.com/wycats/thor/blob/master/thor.gemspec#L21

Yeah, I've got that in mine, too.

Pardot
Jul 25, 2001




redacted

Pardot fucked around with this message at 22:16 on Dec 8, 2013

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Yeah, really wanted to go but filled up before I finalized my travel plans. Oh well.

ZanderZ
Apr 7, 2011

by T. Mascis
Can anyone help me better understand methods? I'm trying to write a method for the current user that currently looks like this.

def current_user= (user)
@current_user ||= user_from_remember_token
end

It seems pretty redundant, especially considering the fact that I have a controller for users and a controller for sessions and current_user is defined the same way, in both. It's also in both helpers.

I'm getting a no method error when I try to use <% if current_user?(display_user.info) %> I assume it's having an issue with the method for current_user or is the error in regards to "display_user.info"?

What's a good format for "current user?" I have it set, so it's dependent on cookies, but I'd rather it just assume that "current user" is the user that's currently logged in. Should I be defining it in the users controller or the sessions controller? I'm pretty good at overcomplicating things.

ZanderZ fucked around with this message at 17:15 on Jan 10, 2012

Lamont Cranston
Sep 1, 2006

how do i shot foam

ZanderZ posted:

Can anyone help me better understand methods? I'm trying to write a method for the current user that currently looks like this.

def current_user= (user)
@current_user ||= user_from_remember_token
end

It seems pretty redundant, especially considering the fact that I have a controller for users and a controller for sessions and current_user is defined the same way, in both. It's also in both helpers.

I'm getting a no method error when I try to use <% if current_user?(display_user.info) %> I assume it's having an issue with the method for current_user or is the error in regards to "display_user.info"?

What's a good format for "current user?" I have it set, so it's dependent on cookies, but I'd rather it just assume that "current user" is the user that's currently logged in. Should I be defining it in the users controller or the sessions controller? I'm pretty good at overcomplicating things.

First of all, a method called "current_user=" is a setter, and the body of your method is a getter. Also, "current_user", "current_user=" and "current_user?" are all different methods, that's why you're seeing a method not found error.

Apart from that I don't know enough about the implementation of your authentication system to be able to say. Are you using a gem for authentication? If you are, you probably don't need to do the implementation for current_user yourself.

Operation Atlas
Dec 17, 2003

Bliss Can Be Bought
I think it helps to enumerate the difference between @current_user, current_user, current_user= and current_user?

@current_user is an instance variable. That is, a value that is owned by your controller instance. In the Rails world a new controller object is instantiated for each request, so your instance variables are "reset" on every request.

current_user is a memoized getter method, and should be like this:
code:
def current_user
  @current_user ||= user_from_remember_token
end
The method is shorthand for two things: 1) If the memo has been set: return the memo, 2) If the memo has not been set: get the value, set the memo to the value, return the memo. This is helpful because the expensive database finds are only executed once per request.

current_user= is a setter method, and should be like this:
code:
def current_user=(user)
  # Do whatever poo poo you need to do to set up your session / cookies
  @current_user = user
end
The important part is that you set the memo to be the user object that was passed in.

current_user? is method that returns a boolean value, and should be like this:
code:
def current_user?
  !current_user.nil?
end

Physical
Sep 26, 2007

by T. Finninho

epswing posted:

I just want to make a quick note here.

RonaldMcDonald's php code is less than 15 lines of simple, easy-to-follow php.
Novo's ruby/rails code is almost 30 lines spread across 4 files (and ends his post with "Simple." :v: ).

If you've never heard of MVC or haven't used any web frameworks before you may think that Novo is nuts. He's not. Although the ruby he posted is definitely more complicated structurally than the equivalent non-framework php, this is actually how anything larger than a very simple dynamic website should be done, with presentation (html) separate from logic (db access et al).


Edit: I know almost nothing about ruby or rails, but something that keeps me from diving in head first is...well, the concept of automated db access in general. Am I really going to let something write my sql for me? I really enjoy hammering out a nice query that does exactly what I need it to do, complete with inner/outer joins, unions, subselects, likes, ins, and whatever else is necessary with the appropriate indexes. For simple "select * from table where col=value" queries fine, do it for me, I won't mind. But for anything complex, can I take over? I know Hibernate allows me to take over when necessary. I don't yet trust the efficiency of a cruise controlled database.

This is from page one, but I just want to jump in here and say that this post really sums up my exprience at the first couple seconds of looking at that code. The .rhtml makes alot of sense. You don't do the whole html, just the tages you need to represent. But until I saw that example I was still lost.

Also what is the deal with always having to inherit form an object?

Novo posted:

If I wanted a page that listed all people ordered by lastname, I could do this:

In app/controllers/person_controller.rb:

code:
class PersonController < ApplicationController
   def list
      @people = Person.find(:all, :order => 'lastname ASC')
   end
end
Here I am saying, "there is an action called list in the person controller, it finds all people ordered by lastname (ascending) and puts the collection in @people". In a real application you would put other actions for managing people here.

In app/models/person.rb:
code:
class Person < ActiveRecord::Base
   def age
      Time.now.year - birthdate.year
   end
end
Defining this data model assumes a table called "persons" (you can override this easily) and is what allows you to find people using Person.find in your controller (above). To make your example more interesting I've defined a simple method which will return the approximate age of the person. This assumes a persons.birthdate datetime column.

In app/views/person/list.rhtml:
code:
<table>
<% @people.each do |person| %>
 <tr>
   <td><%= person.lastname -%></td>
   <td><%= person.firstname -%></td>
   <td><%= person.age -%></td>
 </tr>
<% end %>
</table>
This view simply steps through each person in @people and renders the appropriate HTML. Notice that we are using the age method in our view. We are done. Going to http://myapp.com/person/list would render list.rhtml above. In a .rhtml template (or "view"), statements inside <% %> are evaluated, <%= %> is evaluated and echoed, and ending with -%> suppresses the final newline.

To highlight another convenience of Rails, if I have a site template, I simply put that in app/views/layouts/application.rhtml and it will wrap other views:
code:
<html>
 <head>
  <title>My Site</title>
 </head>
 <body>
  <!-- content gets inserted where you yield -->
  <%= yield -%>
 </body>
</html>
Simple.


Like, how do you know which objects to inherit from? Where is the list at? Right now, those first two parts are really losing me, the missing {} and () sucks too. Why do I have to right end if I can just do } I like the way it looks much better.

And is the lowercase person the same as the uppercase Person ?

kalleth
Jan 28, 2006

C'mon, just give it a shot
Fun Shoe

Physical posted:

Also what is the deal with always having to inherit form an object?

Literally everything in Ruby is an Object. '1' is an object of the String class, 1 is an object of the Fixnum class.

Physical posted:

Like, how do you know which objects to inherit from? Where is the list at? Right now, those first two parts are really losing me, the missing {} and () sucks too. Why do I have to right end if I can just do } I like the way it looks much better.

In the examples given, the models and controllers (Person, PersonController 'classes') build on functionality provided by rails, hence they inherit from ('extend') ActiveRecord::Base class which then provides an ORM around using that object (having it go to the database to retrieve itself, for example, and allowing you to 'save' it, etc).

The controller code is called in specific ways with specific prefixes/suffixes etc hence extending from ApplicationController (which extends from some other ActionController::Base, i think).

Basically, if you didn't extend these classes, you don't get the functionality of rails.

Physical posted:

And is the lowercase person the same as the uppercase Person ?

code:
person = Person.find(:first)
'person' is an instance of the Person class -- in this case, the 'first' instance that could be retrieved from the database (this is equivalent to doing SELECT * FROM people LIMIT 1).

prom candy
Dec 16, 2005

Only I may dance
Just to add to that, you don't always have to inherit. I write classes all the time that don't inherit from ActiveRecord. Inheriting from ActiveRecord is when you have a one-to-one class-to-table mapping with your database. If you want to write a class that has other responsibilities, go hog wild.

If you want to use { and } rather than do and end you can, but the preferred Ruby style is to use do and end for multi-line blocks and { and } for single line blocks.

code:
  people.each do |person|
    person.name = "Hi"
    person.save
  end
vs.

code:
  people.each { |person| person.update_attributes(:name => "Hi") }
(These examples do the same thing).

Finally, not sure who asked it or if it's already been answered, but yes you can craft your own SQL if you need to do something complicated. However, ActiveRecord is powerful and expressive, you don't need to do that very often.

enki42
Jun 11, 2001
#ATMLIVESMATTER

Put this Nazi-lover on ignore immediately!
I do find that I bump up against the limits of "vanilla" ActiveRecord fairly often, but fortunately, ActiveRecord is built on top of Arel, and there's very little that isn't possible with Arel.

It can seem pretty tempting to drop back to SQL, but you are losing some benefits by doing so - for starters, eager loading associations becomes a lot more of a pain, and you won't be able to chain together any pure SQL calls.

Physical
Sep 26, 2007

by T. Finninho

kalleth posted:

Literally everything in Ruby is an Object. '1' is an object of the String class, 1 is an object of the Fixnum class.


In the examples given, the models and controllers (Person, PersonController 'classes') build on functionality provided by rails, hence they inherit from ('extend') ActiveRecord::Base class which then provides an ORM around using that object (having it go to the database to retrieve itself, for example, and allowing you to 'save' it, etc).

The controller code is called in specific ways with specific prefixes/suffixes etc hence extending from ApplicationController (which extends from some other ActionController::Base, i think).

Basically, if you didn't extend these classes, you don't get the functionality of rails.


code:
person = Person.find(:first)
'person' is an instance of the Person class -- in this case, the 'first' instance that could be retrieved from the database (this is equivalent to doing SELECT * FROM people LIMIT 1).

Uhh maybe thats where my confusion coms from, there is no line that says perosn = Person.find

its @people = Person.find.

prom candy
Dec 16, 2005

Only I may dance
The .find method has the ability to return either one object or a collection of objects. Most of the time .find isn't used anymore and convenience methods are used instead, but here's an example. Again, the code below is no longer the correct way to do this:

code:
  # Return the first person in the database
  @person = Person.find(:first)

  # Return all the people in the database as a collection object
  @people = Person.find(:all)
The new and better way of writing the same thing is:

code:
  # Return the first person in the database
  @person = Person.first
  
  # Return all the people in the database
  @people = Person.all
Now, say you had @people, a collection of people, and you wanted to loop through it and print each person's first name. You would define a variable within block scope called "person" and access each person that way:

code:
  @people.each do |person|
    puts person.first_name
  end
In this case, person is defined in the block scope, but you can call that variable anything you want.

code:
  @people.each do |dude|
    puts dude.first_name
  end

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Pretty much. Read up on .where if you're interested in returning collections.

prom candy
Dec 16, 2005

Only I may dance
It would probably be a good idea to check out something like http://railsforzombies.org/

Physical
Sep 26, 2007

by T. Finninho
What do the tops of these files look like? How do they get linked together so that person knows where to get its data from?

prom candy
Dec 16, 2005

Only I may dance
It's split into Model/View/Controller. The framework itself takes care of including all the necessary files so they know how to talk to each other. Let's assume a simple scenario where you have a database table called "people" with columns "first_name" and "last_name". Your goal is to print out a list of these people, ordered by last name, when someone visits http://yoursite.com/people.

First the model (app/models/person.rb). This model doesn't need any code because it inherits from ActiveRecord::Base. That means that you automatically get methods like "all" and "find" and "save." However, if you have any heavy duty business logic you want to include it in the model. In our example I'll be defining a method called "full_name" which just concats the first_name and last_name methods. In my example I use "return" and I also refer to "self.", both of which are unnecessary and frowned upon, but they make it easier to understand in this example.

code:
# app/models/person.rb
class Person < ActiveRecord::Base
  def full_name
    return self.first_name + " " + self.last_name
  end
end
Next up is the controller. The controller is the go-between for your models and your views. This is where you query your model to prepare the variables that you'll use in your view. Any variable that starts with @ will be available in your view. The important thing to look at here is People.order(:last_name) which returns a collection.

code:
# app/controllers/people_controller.rb
class PeopleController < ApplicationController

  # When someone visits /people they will get this method
  def index
    @people = Person.order(:last_name)
  end
end
Finally, the view. This is what the framework will use as a template when someone visits /people

code:
<ul>
  <% @people.each do |person| %>
    <li><%= person.full_name %></li>
  <% end %>
</ul>

Physical
Sep 26, 2007

by T. Finninho

prom candy posted:

It's split into Model/View/Controller. The framework itself takes care of including all the necessary files so they know how to talk to each other. Let's assume a simple scenario where you have a database table called "people" with columns "first_name" and "last_name". Your goal is to print out a list of these people, ordered by last name, when someone visits http://yoursite.com/people.

First the model (app/models/person.rb). This model doesn't need any code because it inherits from ActiveRecord::Base. That means that you automatically get methods like "all" and "find" and "save." However, if you have any heavy duty business logic you want to include it in the model. In our example I'll be defining a method called "full_name" which just concats the first_name and last_name methods. In my example I use "return" and I also refer to "self.", both of which are unnecessary and frowned upon, but they make it easier to understand in this example.

code:
# app/models/person.rb
class Person < ActiveRecord::Base
  def full_name
    return self.first_name + " " + self.last_name
  end
end
Next up is the controller. The controller is the go-between for your models and your views. This is where you query your model to prepare the variables that you'll use in your view. Any variable that starts with @ will be available in your view. The important thing to look at here is People.order(:last_name) which returns a collection.

code:
# app/controllers/people_controller.rb
class PeopleController < ApplicationController

  # When someone visits /people they will get this method
  def index
    @people = Person.order(:last_name)
  end
end
Finally, the view. This is what the framework will use as a template when someone visits /people

code:
<ul>
  <% @people.each do |person| %>
    <li><%= person.full_name %></li>
  <% end %>
</ul>
I am at least familiar with MVC methodology and specifically have experienced using it with PHP and Code Ignitor.

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

What's the question, then? Rails is linking them behind the scenes using the inherited ActiveRecord and ActiveController classes. See your routes.rb for examples of invoking ActiveController methods.

Nybble
Jun 28, 2008

praise chuck, raise heck

prom candy posted:

:words: + code

Thanks for this. I've been working with Rails for the last few months, and while I feel like I've had my nose buried in code books, this was a nice 30,000 foot view.

prom candy
Dec 16, 2005

Only I may dance

Physical posted:

I am at least familiar with MVC methodology and specifically have experienced using it with PHP and Code Ignitor.

The major difference between Rails and CI (in my limited experience with an older version of CI) is that Rails practices what's called "Convention over Configuration." Assuming you follow the Rails conventions of putting your files in the right places and naming them the right things (in relation to your database table names, for example) you don't have to explicitly include any files, it's all done for you. In CI if you want to reference a model from another controller you have to specifically say "i'm going to be working with this model" but you don't need to do that in Rails. You can pretty much access anything from anywhere if you know what it's called.

Look at the index action in the controller and the index.html template (I forgot to mention that the view would reside in app/views/people/index.html.erb). Rails automatically invokes app/views/people/index.html.erb for the action "index" in the controller "People" because that's the convention. If you wanted to you could render something else.

code:
  # app/controllers/people_controller.rb
class PeopleController < ApplicationController

  # When someone visits /people they will get this method
  def index
    @people = Person.order(:last_name)
    render :template => "dudes/list" # This will use app/views/dudes/list.html.erb instead 
  end
end
Similarly, your "Person" model automatically knows it's dealing with your database table called "people" because Rails automatically links an ActiveRecord model with the pluralized version of itself. Again, you're not bound to this, you could just do:

code:
# app/models/person.rb
class Person < ActiveRecord::Base
  set_table_name "dudes"
  
  def full_name
    return self.first_name + " " + self.last_name
  end
end
The idea and the real appeal of Rails (IMO) is that it automatically does all the tedious stuff for you, provided you stick to the conventions.

Adbot
ADBOT LOVES YOU

Physical
Sep 26, 2007

by T. Finninho

prom candy posted:

The idea and the real appeal of Rails (IMO) is that it automatically does all the tedious stuff for you, provided you stick to the conventions.

I'm getting into rails because I had a job interview monday and they are migrating from sharepoint to a new custom solution they want to build. The main lead did some research and said that what you said is why he thought rails will be best. We won't have to take the time to build a database layer inbetween.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply