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
HIERARCHY OF WEEDZ
Aug 1, 2005

My example wasn't perfectly analogous. It would be to create a new Foo based on the condition of an existing Bar.

Adbot
ADBOT LOVES YOU

dustgun
Jun 20, 2004

And then the doorbell would ring and the next santa would come
So, Baltimore it is for railsconf. I think that at least a few attendees will have to be murdered for expectations to be met.

Operation Atlas
Dec 17, 2003

Bliss Can Be Bought

dustgun posted:

So, Baltimore it is for railsconf. I think that at least a few attendees will have to be murdered for expectations to be met.

I didn't go last year, and I'm definitely not going this year. I think the only reason I went in 07-08 is because it was in Portland. Portland > Rails.

Pardot
Jul 25, 2001




I've been the last 3 years, and portland was defiantly awesome. Vegas was fun, but was not at all the right atmosphere. As for baltimore, I'll probably go, but I don't want to be murdered :ohdear:

smug forum asshole
Jan 15, 2005

Pardot posted:

I've been the last 3 years, and portland was defiantly awesome. Vegas was fun, but was not at all the right atmosphere. As for baltimore, I'll probably go, but I don't want to be murdered :ohdear:

Baltimore isn't all crime everywhere. You will be fine unless you get very lost.

hmm yes
Dec 2, 2000
College Slice
That's not what The Wire taught me

Bathroompants
Aug 19, 2002
I think I'm really going to try going for my first time to Baltimore since its a 5 hour drive away from me. Kind of feel weird about going alone and not really knowing anyone though, is that what a lot of people do?

plasticbugs
Dec 13, 2006

Special Batman and Robin
I have an EXTREMELY rudimentary question.

I've set up two models: Games and Consoles
Console has many games
Game belongs to Console

I'm creating New games and assigning consoles to them. How is it that I can say:
game.console.title and get back the title of the console assigned to the game. However, I can't say "console.game" and get back all the games that belong to that particular console.

The Games table is getting the console_id, but the Console table isn't filling up with multiple game_ids as they're being assigned to consoles.

What fundamental ActiveRecord concept am I missing here? Should I be inserting game_ids into the console table at the same time that the console_id is being inserted into the game table? How do I ultimately list all games for a particular console if the console model isn't storing game_id?

EDIT: This is just an exercise as I'm wrapping my head around rails. I won't be putting anything of this nature onto the web.

Here's a pic of my ugly interface so you can see what my New Game action looks like

plasticbugs fucked around with this message at 10:19 on Oct 11, 2009

Sewer Adventure
Aug 25, 2004

plasticbugs posted:


I'm creating New games and assigning consoles to them. How is it that I can say:
game.console.title and get back the title of the console assigned to the game. However, I can't say "console.game" and get back all the games that belong to that particular console.


console.games will return an array of games

plasticbugs
Dec 13, 2006

Special Batman and Robin

Sewer Adventure posted:

console.games will return an array of games

Nope, I'm still getting back an empty array for each console.

Here's my ruby code for assigning a console to a game using a drop-down list:
code:
<%= collection_select(:game, :gameconsole_id, @gameconsoles, :id, :title) %>
And here are my two models:
code:
class Game < ActiveRecord::Base
  belongs_to :gameconsole
end

class Gameconsole < ActiveRecord::Base
  has_many :games
end
And it's working on a per-game basis. I'm able to assign each game a gameconsole. But, when I list each console, I'd like to get back a list of games for that console. Is the only way to do that is by doing a find on @games where gameconsole_id == X?

I thought ActiveRecord provided a way to go through @gameconsole to pull each console's games. Is that an incorrrect assumption?

I think I'm missing an important concept here. I assumed that ActiveRecord automatically handled this without a join table. Aren't join tables mainly for HABTM relationships?

NotShadowStar
Sep 20, 2000

plasticbugs posted:


What fundamental ActiveRecord concept am I missing here? Should I be inserting game_ids into the console table at the same time that the console_id is being inserted into the game table? How do I ultimately list all games for a particular console if the console model isn't storing game_id?


Nope, no need, that's 'has many and belongs to'. AR is smart enough to do backwards association without having to have foreign keys in both directions. When you say has_many :games, and then you say
code:
z = Console.first
z.games
Returns an array of Game objects by the sql query

code:
SELECT * FROM games WHERE console_id = 1
It took me a while to think of relationships the Rails way. It's easy to understand but sometimes I would get confused as to what to say 'has' and 'belongs to'. I saved this picture just in case it goes away as a reference:

http://mboffin.com/stuff/ruby-on-rails-data-relationships.png

e: looking at the classes above I think you're hitting issues with naming conventions. class Gameconsole will look for a table called gameconsoles, what I think you want is class GameConsole, which will look for a table called game_consoles. What's your migration? Did you use script/generate? I highly recommend using script/generate because it'll auto-name everything correctly. Even if that isn't the issue it gets you used to naming conventions to make everything highly readable and consistent.

NotShadowStar fucked around with this message at 22:37 on Oct 11, 2009

plasticbugs
Dec 13, 2006

Special Batman and Robin

NotShadowStar posted:

Nope, no need, that's 'has many and belongs to'. AR is smart enough to do backwards association without having to have foreign keys in both directions. When you say has_many :games, and then you say
code:
z = Console.first
z.games
Returns an array of Game objects by the sql query

code:
SELECT * FROM games WHERE console_id = 1
It took me a while to think of relationships the Rails way. It's easy to understand but sometimes I would get confused as to what to say 'has' and 'belongs to'. I saved this picture just in case it goes away as a reference:

http://mboffin.com/stuff/ruby-on-rails-data-relationships.png

e: looking at the classes above I think you're hitting issues with naming conventions. class Gameconsole will look for a table called gameconsoles, what I think you want is class GameConsole, which will look for a table called game_consoles. What's your migration? Did you use script/generate? I highly recommend using script/generate because it'll auto-name everything correctly. Even if that isn't the issue it gets you used to naming conventions to make everything highly readable and consistent.

That helps a lot. Thanks. I think my bigger issue was with using my app's "script/console" to update each record and it wasn't showing the state changes on my other model's instances. When I actually got to coding my views, the pages displayed as they should with each console spitting out their associated games and each game knowing which gaming console it belonged to.

Thanks again, I'm saving that chart. It will be very handy.

Molten Llama
Sep 20, 2006

plasticbugs posted:

That helps a lot. Thanks. I think my bigger issue was with using my app's "script/console" to update each record and it wasn't showing the state changes on my other model's instances.

If you're not explicitly calling save after making a change, there has been no change as far as the app's concerned. It's pulling from the DB, and without a save, the DB is untouched.

plasticbugs
Dec 13, 2006

Special Batman and Robin

Molten Llama posted:

If you're not explicitly calling save after making a change, there has been no change as far as the app's concerned. It's pulling from the DB, and without a save, the DB is untouched.

You're right. I wasn't calling save on the right instance. Seems to be working as advertised, now. Thanks.

bitprophet
Jul 22, 2004
Taco Defender

plasticbugs posted:

You're right. I wasn't calling save on the right instance. Seems to be working as advertised, now. Thanks.

The main thing to grasp here, and this goes for any ORM, not just Rails', is that there's your in-memory object and your database row, and they're actually completely distinct from one another until something happens to either read from, or write to, the database.

(N.B. re: the following, my knowledge may be out of date -- I am cursed to maintain a poorly written Rails 1.2 project at work these days, it's my albatross.)

In this case, as mentioned, you needed to explicitly save the record to the database after modifying it in the Ruby shell. Conversely, once you've gotten an object out of the database by doing Console.first or Console.find, it won't reflect any changes made to other copies of the same object elsewhere in memory, or in the database, unless you call its reload method or otherwise tell it to refresh itself.

Rails tends to make this more confusing than it could be, because some actions are implicit, like assigning some related objects. After reading the most recent API docs I wonder if I'm misremembering or if it changed in Rails 2, but I believe assigning to a "parent" object (e.g. game_instance.console = console_instance) often saves the child right away. Certainly, going by the link, there are still some examples of automatic saving around, even if the one I just gave isn't correct.

NotShadowStar
Sep 20, 2000

bitprophet posted:

The main thing to grasp here, and this goes for any ORM, not just Rails', is that there's your in-memory object and your database row, and they're actually completely distinct from one another until something happens to either read from, or write to, the database.

(N.B. re: the following, my knowledge may be out of date -- I am cursed to maintain a poorly written Rails 1.2 project at work these days, it's my albatross.)

In this case, as mentioned, you needed to explicitly save the record to the database after modifying it in the Ruby shell. Conversely, once you've gotten an object out of the database by doing Console.first or Console.find, it won't reflect any changes made to other copies of the same object elsewhere in memory, or in the database, unless you call its reload method or otherwise tell it to refresh itself.

Rails tends to make this more confusing than it could be, because some actions are implicit, like assigning some related objects. After reading the most recent API docs I wonder if I'm misremembering or if it changed in Rails 2, but I believe assigning to a "parent" object (e.g. game_instance.console = console_instance) often saves the child right away. Certainly, going by the link, there are still some examples of automatic saving around, even if the one I just gave isn't correct.

Yes, I was just going to link the API on saving. Yes it is slightly confusing, but for basics the two things that auto-save records (unless the :autosave property of set, as stated) are .create and adding a new association to the .games array like Console.find_by_name('Super Nintendo').games.push(Game.create(:name => 'Shaq Fu') ).

(You don't actually want to write it like that though, that's too confusing, but it show's how it works)

Anything else requires an explicit .save, which is good because you know exactly when the record is being saved. The two mention above are for convenience because you do those so very often.

Another thing, anything and everything, whenever it writes back to the database, no matter if it's automatically saved like .create or explicitly like .save always always always goes through validations unless you really tell it to save_without_validation. Which reminds me, your Game class really should look like:

code:
class Game < ActiveRecord::Base
  belongs_to :game_console
  validates_presence_of :game_console_id
  validates_numericality_of :game_console_id
end
You might think this is silly, but believe me this has actually caught me from making huge mistakes when designing complex forms that have one to many relationships.

Pardot
Jul 25, 2001




The other non-obvious, big thing you need to get in the habit of is to use add_index in your migrations on at least your foreign keys. Documentation.

hmm yes
Dec 2, 2000
College Slice
Is there anything beyond the api entry for add_index that explains what an index does, how it is good, and general introductory things like that?

Pardot
Jul 25, 2001




atastypie posted:

Is there anything beyond the api entry for add_index that explains what an index does, how it is good, and general introductory things like that?

It tells your database to index that column, like you'd do with any sql database rails using it or not. It's important if you're going to be doing JOINs with that column. Also if you're going to use any of active records' find_by_<whatever> they probably should be indexed too.

Jamis Buck does a good job explaining here: http://weblog.jamisbuck.org/2006/10/23/indexing-for-db-performance
And thoughtbot: http://robots.thoughtbot.com/post/163627511/a-grand-piano-for-your-violin

NotShadowStar
Sep 20, 2000
Quick explanation of indices:

An index on a column in a separate entity in the structure of the table that is exactly what it says, and index to help the database engine find something quickly. Its like an index of a book. If you ask the database 'I want to find record #65,237' then the database engine looks at the index which tells it exactly (or close to) where record # 65,237 is in the database data. Otherwise, the database engine has to go row by row and ask 'Are you record number #65,237? No?" until it exhausts the entire table or it hits the limits of the query. This as you can imagine this is an exceptionally slow process and if at all possible should be avoided.

The tradeoff is obviously you need the disk space and memory overhead available to store indices, and the indices of the table will get bigger as tables get bigger. So you don't want to add an index to every single column, but you should at least add an index to every column used in joining.

Most of the time this doesn't matter if you're doing tiny sites, but if you get any sort of load, you'll see it. I use this all the time, it is extremely helpful

http://github.com/dsboulder/query_reviewer

hmm yes
Dec 2, 2000
College Slice
Thanks to both of you, that was exactly what I was hoping to see.

plasticbugs
Dec 13, 2006

Special Batman and Robin

NotShadowStar posted:

Another thing, anything and everything, whenever it writes back to the database, no matter if it's automatically saved like .create or explicitly like .save always always always goes through validations unless you really tell it to save_without_validation. Which reminds me, your Game class really should look like:

code:
class Game < ActiveRecord::Base
  belongs_to :game_console
  validates_presence_of :game_console_id
  validates_numericality_of :game_console_id
end

This is great advice, too. I'm seeing the importance of validations and well-written error messages as I get deeper.

Pardot posted:

The other non-obvious, big thing you need to get in the habit of is to use add_index in your migrations on at least your foreign keys. Documentation.

I'll start making it a point to add indexes on all my foreign keys. I'd like to think I'm working towards "best practices", so thanks for the advice.

Hammertime
May 21, 2003
stop

bitprophet posted:

The main thing to grasp here, and this goes for any ORM, not just Rails', is that there's your in-memory object and your database row, and they're actually completely distinct from one another until something happens to either read from, or write to, the database.

Any ORM except for (N)Hibernate (out of the box) that is. Even when you don't explicitly save, crazy persistence magic still happens! </tangent>

Anveo
Mar 23, 2002
If anyone is looking for production ready example applications to learn from, I have started compiling a list in a blog post: http://jetpackweb.com/blog/2009/10/14/high-quality-ruby-on-rails-example-applications/

Hope it's useful to someone.

smug forum asshole
Jan 15, 2005
anyone ever have problems with paperclip recognizing only .tga files? other formats seem to work fine.

dustgun
Jun 20, 2004

And then the doorbell would ring and the next santa would come
Without having any experience using paperclip, could it be an ImageMagick problem?

smug forum asshole
Jan 15, 2005
good question! just went to the command line and used the imagemagick 'convert' command to convert one of the tga files in question to a jpg. no problems there, so I don't know that imagemagick is to blame.

NotShadowStar
Sep 20, 2000
So people who are good with RSpec or Cucumber testing...

I'm creating data models (for another application but it will be moved to rails, drat legacy projects still in use). One model class takes data from several other classes, calculates and returns values based upon the data in those other classes. The other classes are mostly just 2D arrays with some helper methods, so I just made tests that ensure they store data properly using random data and they respond to the appropriate methods. Like such:

http://pastie.org/664105

So that's all well and good, but where I am running into an issue is trying to ensure that another class that takes several of the Plate classes and performs some calculations will always function properly given known data. I've been looking around and the consensus is that fixtures are evil, but I can't figure out how to perform a calculation test to ensure that the calculations are performed properly without using known input and output data. I've read about mocks and stubs but I gather that those are helper dummy objects that ensure that you always get the return values you want without relying on data. That's not what I want, the functionality I can ensure through the testing of the Plate class, but another class is performing calculations that need to be ensured that it always works. The only way I can think of is create serialized/marshalled objects that contain known input and output data. Am I missing something here?

Operation Atlas
Dec 17, 2003

Bliss Can Be Bought

NotShadowStar posted:

So people who are good with RSpec or Cucumber testing...

I'm creating data models (for another application but it will be moved to rails, drat legacy projects still in use). One model class takes data from several other classes, calculates and returns values based upon the data in those other classes. The other classes are mostly just 2D arrays with some helper methods, so I just made tests that ensure they store data properly using random data and they respond to the appropriate methods. Like such:

http://pastie.org/664105

So that's all well and good, but where I am running into an issue is trying to ensure that another class that takes several of the Plate classes and performs some calculations will always function properly given known data. I've been looking around and the consensus is that fixtures are evil, but I can't figure out how to perform a calculation test to ensure that the calculations are performed properly without using known input and output data. I've read about mocks and stubs but I gather that those are helper dummy objects that ensure that you always get the return values you want without relying on data. That's not what I want, the functionality I can ensure through the testing of the Plate class, but another class is performing calculations that need to be ensured that it always works. The only way I can think of is create serialized/marshalled objects that contain known input and output data. Am I missing something here?

For unit tests, use mocks and stubs. You really only want to be testing one method at a time.

For functional tests, try using factories. There are several libraries out there (Object Daddy, Factory Girl, etc) that help you generate decent test data using pure ruby.

NotShadowStar
Sep 20, 2000
13 minutes later and I get a great answer. I <3 you guys.

Never heard of object daddy, but seen Factory Girl and never found a use for it. Looking at Object Daddy brought me to http://b.logi.cx/2007/11/26/object-daddy which was long winded, funny as hell but also explains exactly what I'm doing and why it's wrong. Awesome. It also shows why I totally love Ruby minded people, since they care about making things work well and maintainable no matter the situation, instead of the 'eh gently caress it, that'll do' attitude that's pervasive elsewhere.

Anveo
Mar 23, 2002

NotShadowStar posted:

So people who are good with RSpec or Cucumber testing...

I would also highly suggest buying this (e)book http://www.pragprog.com/titles/achbd/the-rspec-book

Also, the link I posted a few posts above has links to open source projects that have really good rspec and cucumber test coverage. Might be helpful if you are just starting to use RSpec.

NotShadowStar
Sep 20, 2000
And that I did. I love pragprog books, I learned Rails from the Rails book. Thanks!

keep it down up there!
Jun 22, 2006

How's it goin' eh?

I got a few getting started questions.

I've dabbled in RoR briefly before in an environment setup by using Instant Rails and NetBeans as my IDE.

I wanna get back into it, and every tutorial I read involves using the command prompt for things, and I definitely didn't do that before outside of raking the DB.

What's the standard way to setup and work in RoR on Windows?

I guess I should add I plan to use Facebooker as well, as I wanna make a small app there. Is this still the best? It seems RFacebook is no longer updated.

Thanks

Anveo
Mar 23, 2002

BUGS OF SPRING posted:

I got a few getting started questions.

I've dabbled in RoR briefly before in an environment setup by using Instant Rails and NetBeans as my IDE.

I wanna get back into it, and every tutorial I read involves using the command prompt for things, and I definitely didn't do that before outside of raking the DB.

What's the standard way to setup and work in RoR on Windows?

I guess I should add I plan to use Facebooker as well, as I wanna make a small app there. Is this still the best? It seems RFacebook is no longer updated.

Thanks

Windows really isn't the ideal environment, but either way you are going to have to get used to using the command prompt and probably some basic unix. I don't know if there is an official best way, but the last time I helped someone get setup in Windows Cygwin was able to handle pretty much everything. I would also suggest accessing it via Console2. You can install ruby with Cygwin's package manager, and then manually build the 'rubygems' tool from sources.

There are installer packages out there, but you really should learn how to set things up.

I would really suggest just dual booting with Ubuntu or something. There will be much less friction getting setup and much better information on how to get started from scratch.

smug forum asshole
Jan 15, 2005

Anveo posted:

I would really suggest just dual booting with Ubuntu or something. There will be much less friction getting setup and much better information on how to get started from scratch.

This is my suggestion too.

NotShadowStar
Sep 20, 2000
Rails still is a huge pain on Windows and not recommended. You are correct that most of the things are typically done command line, but some sort of IDE can perform the same functions that the command line does. I wouldn't be afraid of the command line though, Rails is very well organized for the most part (there is some confusion why you need to do script/generate to make things but rake for others).

If you're completely stuck on Windows, get Virtualbox and throw Ubuntu in it... ugh wait Ubuntu is its own pit of hell with Ruby. The Ubuntu Ruby maintainer doesn't do a good job and it frequently doesn't work without a lot of fuss. Maybe someone can say if it's better in 9.10 or if another distro has a better out of the box Ruby configuration.

(FYI, not trying to be a human being, but Apple really has the best out-of-the-box Ruby configuration. Install 10.6, open terminal, 'sudo gem update' to make sure all libraries are up to date and you're golden)

Pardot
Jul 25, 2001




It's really a mystery to me why ruby on ubuntu sucks so much. But it does. Last time I had to set up a ubuntu it was to run our CI server, and I just went straight for ruby enterprise edition + passenger and never touched the apt version of ruby, and everything went a lot smoother.

keep it down up there!
Jun 22, 2006

How's it goin' eh?

Oh I'm certainly not afraid of the command line and have no issues using it, I just wasn't in the old setup I had so figured I'd ask.

Sadly I am stuck with Windows and I'm not interested in dual booting as I can't access my other work and apps while I work on this. Can't really afford a Mac either, sadly.

So I guess I should setup a VM with Ubuntu then, but that also sucks? :confused:
Shame I can't VM a Mac OS.

Ghotli
Dec 31, 2005

what am art?
art am what?
what.
Ubuntu 9.04 came with much better support for Ruby 1.8 than previous versions. Ruby 1.9 on the other hand needs to be built from source. Apt ships with 1.9.0 and 1.9.1 is the stable version now. I found this out the hard way quite recently.

Adbot
ADBOT LOVES YOU

hmm yes
Dec 2, 2000
College Slice
You could try installing and upgrading instantrails as done on this blog post. This would have the advantage of you being familiar with instantrails. Not sure I would recommend it. At least on Windows you get to use e text editor which has come a long way and is a pretty solid alternative to textmate. I wish textmate had the tree-history for undo/redo, that poo poo is the best.

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