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
NotShadowStar
Sep 20, 2000
The / in the URL isn't a problem, this is done all the time:

/2008/15/12

by doing:

map.connect ':year/:month/:day', :controller => 'blog', :action => 'by_date'

So you can do

/cidr/ip/mask as

map.connect 'cidr/:ip/:mask', :controller => 'cidr', :action => 'whatever'

Then if you want a helper method you'll have to add a to_url method in your cidr controller like skidooer mentioned. Unless I'm totally off on what you're trying to do

Adbot
ADBOT LOVES YOU

NotShadowStar
Sep 20, 2000
There is also RMagick, which enables you to call ImageMagick APIs in Ruby. ImageMagick has usually been lovely to install in my experience though, doubly so on OSX.

http://www.imagemagick.org/RMagick/doc/comtasks.html#convert

NotShadowStar
Sep 20, 2000
map.resources is a shorthand that creates routes for the methods destroy, update, edit, show, create, new, index. You have the method 'display' which isn't explicitly mapped yet.

So when you do app/display/1 the 1 isn't caught as :id, you have to create a new route to do that. I think instead of :members you're looking for :collection but I've never actually added routes in that manner and the documentation is sparse.

Although what's concerning to me is why you need a separate 'display' method when 'show' is supposed to do exactly what you're doing (show a single record).

That's my theory, you can see if I'm off by doing in the controller (temporarily to figure out WTF)

raise ApplicationError, 'No id!' unless params[:id]
@artwork = Artwork.find params[:id]

NotShadowStar fucked around with this message at 00:00 on Dec 20, 2008

NotShadowStar
Sep 20, 2000
Whoops, there's no such class as ApplicationError but it should still crash and burn just the same. You could just raise Exception. SInce it's not anyway, that's making me wonder what's going on. What's the URL you're using/generating? It should look like app/artwork/display/1. Also what does rake routes say? FURTHERMORE,..;!! if you change your routes I find it's best to restart the server, it seems to act funky even in devel mode I've found.

NotShadowStar
Sep 20, 2000
Is there a cleaner way of handling the output of validation errors without monkeypatching ActionView::Base.field_error_proc ? I really don't like how it just injects html in the view when I have a nice system using the flash for displaying errors. I have this code, and it's fine:

code:
   
 @person = Person.new params[:person]
    if @person.save
      flash[:notice] = "#{@person.first_name} #{@person.last_name} was created"
      redirect_to "/admin/users"
    else
      flash[:error] = @person.errors.full_messages.collect {|m| m + "<br />"}
      render :action => 'new'
    end
But when validations fail that happens plus the html injection from field_error_proc. I could override field_error_proc and just make it return but ugh.

NotShadowStar
Sep 20, 2000
Digging into the depths of the Rails wiki, home of abandoned and unfindable pages brings up

http://wiki.rubyonrails.com/rails/pages/HowtoChangeValidationErrorDisplay

So yeah, that works then. Use my notification system to display the errors and use the proc that's fired on validation fail to add a "FAIL" class to the errant fields.

Awesome.

NotShadowStar
Sep 20, 2000
So next up on the list is I'm writing a model for handling experiment data. Experiments are always done on plates. Plates, in my context, are generally a 2d array that holds stuff. In a separate project I wrote a basic Plate class that's pretty much a 2d array with pretty accessors with other helper stuff, and specialized Plates for their own experiment are subclasses and add their own stuff.

Since I want to store pretty much everything in the DB as possible, I want to store all experiment data in the database with models. Problem 1) The table is going to get large by MySQL standards. I've been considering a design of each row of the database is 1 element in the 2d array, identified by columns in the table that correlate to the position and id # of the experiment plate. Right off the bat I'd be importing about 15,000 experiments, and each experiment can have up to 384 elements (more like an average of ~ 330) so bam that's ~4.95 million rows and probably grow another 1-2 million a year. That's just for one type of experiment, there will be others that will add other millions of rows in this manner to other tables. Other information systems that do something similar to what I'm doing have the same strategy, but they use higher end databases and I understand MySQL might not like this.

The other thing is since there will be several models that are similar but have different properties for different types of experiments or similar data I feel like I should be looking into writing an acts_as, but I don't know the first thing about that.

NotShadowStar fucked around with this message at 19:59 on Jan 2, 2009

NotShadowStar
Sep 20, 2000
Okay I redefined my original problem and came up with a much better solution.

Now I'm wondering if some AR gurus can help out with this. I have this first-stab design (in migration format)

code:
class CreateSdsExperiments < ActiveRecord::Migration
  def self.up
    create_table :sds_experiments do |t|
      t.integer :experiment_id
      
      t.integer :sds_plate_id

      t.integer :stock_plate_1_id
      t.integer :stock_plate_2_id
      t.integer :stock_plate_3_id
      t.integer :stock_plate_4_id
      
      t.integer :snp_1_id
      t.integer :snp_2_id
      t.integer :snp_3_id
      t.integer :snp_4_id
      
      t.string :layout_type

      t.timestamps
    end
    
    add_index :sds_experiments, :experiment_id
    add_index :sds_experiments, :sds_plate_id
    add_index :sds_experiments, :stock_plate_1_id
    add_index :sds_experiments, :stock_plate_2_id
    add_index :sds_experiments, :stock_plate_3_id
    add_index :sds_experiments, :stock_plate_4_id
    add_index :sds_experiments, :snp_1_id
    add_index :sds_experiments, :snp_2_id
    add_index :sds_experiments, :snp_3_id
    add_index :sds_experiments, :snp_4_id
  end

  def self.down
    drop_table :sds_experiments
  end
end
Essentially an SdsExperiment is nothing more than a fuckoff join table. The interesting part is that 2 sets of fields, the stock plates and the snps should can reference one stock plate or one snp.

If I just needed one then that's easy, SdsExperiment belongs_to :stock_plate and StockPlate has_many :sds_experiments. However, I need up to 4 stock plates, and the order of them is important (I need to know what stock plate 1 is). Essentially I want to say something like belongs_to :stock_plate, :using_instance_method => :stock_plate_1. So in the end I can do something like

Experiment.find(1).sds_experiment[1].stock_plate_1.clownfarts

If this makes any sense at all...

NotShadowStar
Sep 20, 2000
Since nobody cares I'll just put this up anyway. I solved the problem of one model inheriting from another multiple times while keeping track numeric associations like this

code:
class SdsExperiment < ActiveRecord::Base
  has_one :plate_1, :class_name => 'StockPlate', :foreign_key => :plate_1_id
  has_one :plate_2, :class_name => 'StockPlate', :foreign_key => :plate_2_id
  has_one :plate_3, :class_name => 'StockPlate', :foreign_key => :plate_3_id
  has_one :plate_4, :class_name => 'StockPlate', :foreign_key => :plate_4_id
  
  has_one :snp_1, :class_name => 'Snp', :foreign_key => :snp_1_id
  has_one :snp_2, :class_name => 'Snp', :foreign_key => :snp_2_id
  has_one :snp_3, :class_name => 'Snp', :foreign_key => :snp_3_id
  has_one :snp_4, :class_name => 'Snp', :foreign_key => :snp_4_id
  
end
and that works totally fine.

NotShadowStar
Sep 20, 2000

mister_gosh posted:

I'm considering learning and writing a RoR program(s) basically for the hell of it, to learn it. I have a need for a web application that is database dependent (Oracle 10g). If I do not go with RoR there is no way I'd even consider PHP, I'd use Java, JSP, Javascript, etc.

So, given my background and disapproval of PHP, does this sound like a wise use of my time? I'm curious just so I can put another skill under my belt, but that's probably the wrong reason to get into this.

Also, can RoR scripts be runnable from a command line if I had such a use? Can it communicate with COM objects?

Learn RoR without the idea of COM, just learn Rails as Rails first. I've been running into a lot of things that Rails doesn't do automatically and it's difficult navigating around the core trying to figure out where I should modify things. Once you have a grasp on how a Rails application works, then you should think about where you should hook into external objects using non-Rails ways. (I'm guessing you're using COM as a broker for proprietary data, in which case you'd create a non-ActiveRecord model using Win32API and create methods in the model to interact and get data)

NotShadowStar
Sep 20, 2000
Ah yes, the Ruby install in Ubuntu is kind of half-broken because of bad choices, and unfortunately the maintainer still hasn't fixed it.

I remember you have to install the openssl devel libraries, then getting the Ruby core source, then recompiling OpenSSL from there

http://www.slashdotdash.net/2007/06/27/problem-with-openssl-with-ruby-1-8-6-on-ubuntu-fesity-7-04/

However since you're at that point I'd just recompile Ruby 1.8.7 from source anyway and replace the unoptimized Ubuntu version, which is 1/2 has fast as a compile from scratch version. No idea why. (Install from source is really, really easy. Get source, extract, cd ruby-src, ./configure && make && sudo make install. Done)

http://antoniocangiano.com/2008/12/09/the-great-ruby-shootout-december-2008/

NotShadowStar fucked around with this message at 01:04 on Feb 19, 2009

NotShadowStar
Sep 20, 2000
Install the sqlite devel libraries for Ubuntu and redo the gem installation.

Ruby can either have pure Ruby based extensions, or extensions built on C, much like Python. If you're building a C extension, rubygems will tell you, and if it fails you need to solve it like you would any compiled program. Usually things are C extensions to hook into external libraries and provide a bridge, like sqlite, or if they need to be REALLY fast like the Hpricot XML parser.

NotShadowStar
Sep 20, 2000

Hop Pocket posted:

Not necessarily a Rails question, but more of a Ruby / Module question. I recently wrote a module to try and wrap up some functionality that was duplicated across parts of our application. In doing so, I developed the module in isolation, creating public API methods along with private methods to help with the heavy lifting.

Once I mixed in the module into my controller, I found that a method that my controller defined was always taking precedence of the same named method in the module that was being mixed in. This makes sense given the nature of Ruby method dispatching. It starts at the receiver's class and proceeds up the Class/Module hierarchy, finding the first method that matches the name. Of course, it would find the method defined in the object's Class before it found the method in the mixed-in Module.

This made me really think twice about abstracting out functionality into Modules. I'd really love to have a way to have Ruby dispatch method calls first to the type from whence the method came instead of starting over with the normal dispatch routines coming from the object class itself.

This gist gives an example of what I'm talking about. #hello invokes the Person implementation of #saying rather than the Greeter method of #saying. #hello_two bypasses this through clunky method binding to execute the Module method rather than the original Class method.

Am I using Modules incorrectly here?

Use a nested module, and only include the top module. This is what you do when you write plugins to ensure no name collisions

http://wiki.rubyonrails.org/rails/pages/HowToWriteAnActsAsFoxPlugin

code:
module Clownfarts
  module Beefsteak
    
    class << self
      def duck_fuck
        "minced assholes"
      end
    end
    
  end
end

include Clownfarts

p Beefsteak.duck_fuck

NotShadowStar
Sep 20, 2000
Leaving in one minute but I don't know if that will even work, since you got to method_missing through a render with a missing template (explicit or implicit) so you'll get a double render error when you get that far. I think. You probably want to look at rescue_action_in_public

NotShadowStar
Sep 20, 2000
Okay, even better, Rails now has a rescue_from construction. Provide rescue_from with an exception class and you can invoke a method to handle that. Don't raise exceptions in the other methods though or you could be caught in a loop. These are the end of the chain.

Also remember that 404s and 500s are handled differently in production and development environments. Remember to switch your env to production to test and make sure it works the same.

code:
class ApplicationController<ActionController::Base
  rescue_from ActionView::MissingTemplate, :with => :missing_template
  
  private

  def missing_template(exception)
    render :text => 'You forgot your template dumbass', :status => 404
  end
  
end

NotShadowStar
Sep 20, 2000

chemosh6969 posted:

That got me closer. I did script/generate model YEAR1, but when I tried to pull the first record it died from trying to pull it from table YEAR1s

Use ActiveRecord without Rails first, just connect using AR and figure out what you need to do from there, then take that knowledge back into Rails. I learned AR way before I touched a Rails app, it helps.

atastypie posted:

Has anyone used hpricot or similar to screen scrape pages that are heavy on ajax/javascript? Right now all I am getting returned is the ol 'your browser needs to support javascript' message when I try to pull down a page.

Try WWW:Mechanize instead. I use it to interact with a javascript-based login integration site, but I didn't want to redirect to it so I wrapped in in a class that uses Mechanize instead.

NotShadowStar
Sep 20, 2000
If you've never done any web development ever, Rails is going to be really painful to learn and you're going to make a terrible app. Keep this in mind.

NotShadowStar
Sep 20, 2000

theEZkill posted:

Hey guys- thanks for the advice. I just got that twitter script. Like I said before I'm a complete newb at this and care barley pull off a "Hello World".


Any tips on how I should tackle this?

Yeah try and figure out what the gently caress is going on. Why is Mechanize needed for a Twitter app? Also what you have going on looks far more convoluted that what it should be. What is this Ruby program, can you show some of it or something? This smells of something designed by someone who used to be a Java person and is making things way way way overcomplicated.

NotShadowStar
Sep 20, 2000

Sewer Adventure posted:

Moving to Rails 3 won't be so bad. Moving to ruby 1.9 is going to be a bitch.

I still don't know what the gently caress the core Ruby team was thinking. They improved the core aspects of the interpreter that were the primary weaknesses, the GC and execution speed, and it was amazing. Then they go and make fundamental changes to the language AT THE SAME TIME. ARGH.

On the other hand, I'm getting kinda good at tracking down 1.9 issues from libraries, fixing them and submitting patches.

NotShadowStar
Sep 20, 2000

Sewer Adventure posted:

Please do ferret :)

Oi, I took a look and it looks like a weird C extension that bridges an external library to Ruby. Those are no fun, I tried to work on RSRuby and eventually gave up to do something productive.

quote:

'm probably doing this completely rear end backwards, but I've got my rails application connecting to a telnet server and I'm having a hard time finding a way to show the output.

What I'd like to do is have my messages from the server thread append the new message to the bottom of a text box I have on my page. I can't figure out how to have the method in the helper file thats being called do something like $('destinationDiv').innerHTML += newLineOfText

Anyone have any suggestions?

With RJS, it looks like you're using jQuery and I don't know the answer offhand but jRails should translate appropriately

page.insert_html :bottom, :destinationDiv, {string html or :partial =>}

NotShadowStar
Sep 20, 2000
Did you do rake db:sessions:create ?

NotShadowStar
Sep 20, 2000
Because that sounds positively insane.

The fastest thing I can think of is a custom AR class with before_save and after_load that'll eval the proc as it goes in/out of the table. eval is slow as hell on 1.8 so that may not work out for you, I'll have to dig into the corners of the Rails book for the serialization stuff.

tl;dr it's entirely possible but dear god why.

Reminds me of this crazy dude I know who created a biological information system in .NET. The entire program ran out of some bizarre self compilation that was stored in an MSSQL DB. Each table had rows and columns that were binary blobs that contained pre-compiled .NET CLR code. The main program was a controller that fetched and concatenated the relevant bits from the DB then threw it at the CLR to execute. Of course it could be self-modifying too so what was executed might modify other pre-compiled binary blobs and :psyduck:

NOBODY understood it but on the other hand he's pretty much set for life. What you guys are asking reminds me much of that insanity.

NotShadowStar
Sep 20, 2000
Smallest I've done recently is a basic data collection form with a few fields. With templates it took about 15 minutes from 'rails fartlicker' to adding a Mongrel service to a production server.

For super small there's always PHP, but everything I've ever done has never stayed super small despite the initial conversations so personally I'll do Ruby-CGI or Camping+AR unless there's a dire need for PHP.

NotShadowStar
Sep 20, 2000
Yeah I didn't want to deal with it since the server already serves PHP (4 oh god) with Apache. It's an internal app so I just did a mongrel service on a non-standard port.

NotShadowStar
Sep 20, 2000

Magicmat posted:

Also, while I'm here, what is the most recommended Ruby interpreter to deploy? I know Ruby Enterprise Edition is supposed to be 1.8.6 but not suck so much, but 1.9.1 is supposed to be hella fast, and Rails just got updated for it. However, I also know that other items apparently don't yet support Ruby 1.9. Assuming I'm not using a whole pile of weird plug-ins and gems, is there anything in the standard Rails ecosystem or commonly used 3rd party code/plug-ins that does not like 1.9? I've also seen good speed results from JRuby (which apparently Rails also supports, I think?) Same questions there, too.

Rails 2.3 is finally 100% working for 1.9.1. A lot of the common gems work for 1.9.1 without issue. A big one is Mongrel almost works but it require a find/replace in the C file and then you're good to go.

Some use JRuby for production servers and I guess it'd be neat to latch onto existing Java libraries if you have the need, but the startup time is atrocious being the JVM and all. It would not be fun to develop on. Also when you're using JRuby there needs to be JRuby specific gems versions if the original gem is C-based.

NotShadowStar
Sep 20, 2000
The Rails team is doing a big bug smash push this weekend. Lots of help needed!

http://weblog.rubyonrails.org/2009/7/28/rails-bugmash

NotShadowStar
Sep 20, 2000

Panic! at the Fist Jab posted:

I can't wait to see the results of this. I love it when good software gets better in leaps and bounds because of the community's passion. Wish I had the chops to contribute.

You don't have to be sufficient to work on the core. You can do other things to, combing Lighthouse and merging duplicate tickets, highlighting and merging duplicate patches on github, matching Lighthouse tickets with github patches and so forth!

Operation Atlas posted:

Upgraded a Merb app that uses a custom Couchdb adapter to 1.9.1 and it was fairly easy. Only two or three fixes were necessary. It gave me a chance to clean up my gem situation, so now almost everything is vendored- my only system gems are rake, fastthread and passenger. Overall I'm pretty happy with it- ordered hashes are great, and I think I'm going to like the new hash syntax. I haven't delved into many of the other changes.

Speed-wise I really can't see a difference. My test suite runs in the exact same amount of time- ~0.8 seconds for unit and ~5.4 seconds for functional. I thought it would cut it down by like 20% but the difference is negligible if it is even faster at all. I suppose most of the time in tests is IO (database, etc), so I don't think there would be much difference regardless of the language.

There's a lot of people on the RUBY IS SLOW GOD THIS LANGUAGE SUCKS* for some reason but with today's CPUs execution speed is rarely the problem. I wish the Yellowpages.com guys would put up their presentation from Railsconf the other year but they said that the Rails request chain was actually not a problem using 1.8.7, it was actually the Oracle DB couldn't handle the amount of requests and was stalling out so they had to cluster and round robin Oracle.

*from Perl-head colleagues. It's true, Perl is hella fast but it's so hard to figure out what it's doing and the same perl-heads would tell me 'don't worry about what it's doing just do it'. So I did a comparison project for genome sequence alignment in Perl and Ruby. I just did it straight up, load a genome into memory and then create hash blocks. I could never get it to work with Perl, it would eat about 10gb memory then crash. Ruby used size of genome string + (size of genome string / 31) bytes of memory and happily did what I wanted. 1.8.7 was really dog slow, lik several minutes to finish whereas 1.9.1 does it in less than a minute.

NotShadowStar
Sep 20, 2000

Myrddin Emrys posted:

Total newbie here, just picked up my first RoR book and tried my hand at installing it on Linux.

Dear God, I have the anti-Linux touch. Give me a Linux box, any box, and I will crash it within minutes doing normal things.

Installation of ruby 1.9 was a success, as was gems. Installation of rails failed, because as it turns out OH WAIT ruby wasn't installed. Synaptic and apt-get both reported that ruby was installed, but when I checked the location it spit out, there was nothing there. No folder, no files, nothing. It lied to me :(

So, new distro, and here we go again.

I really don't want to be a human being, but do you have a Mac around? 10.5 works completely out of the box, Apple made everything work perfectly, all you need to do is 'sudo gem update' from a fresh install and you're ready to rock.

I have to go through a few pits of hell every time I try and get Ruby going on Ubuntu. They way the maintainer packaged it makes it all kinds of hosed up. I always end up compiling from source, but then I have to track down a dozen -devel libraries from the repos.

NotShadowStar
Sep 20, 2000

Myrddin Emrys posted:

No, sorry. I had a macbook a year or so ago but I couldn't stand the keyboard. I am a fast typer and it literally could not keep up with my typing, so I ditched it. Got a Toshiba Satellite but that fell off a bus and broke. I'm working now on a netbook (which I am pleasantly surprised runs Linux and Windows 7 incredibly well).

I no longer have a Windows install on it though. I'm also shopping around for a kickass but relatively inexpensive gaming laptop, but the netbook's all I've got for now.

Don't ever try and work with Ruby on Windows. Lots of C-based Ruby libraries expect gcc which of course you don't get on Windows. Either the maintainer or some volunteer built a binary for you to use or you're totally screwed. sqlite is a major one. I've been doing Ruby for about 4-5 years and I still hit a brick wall hard when it comes to working on Windows.

I can try and walk you through a compile and install, or if you can give a user-level temporary shell I can build everything and you can do the final install. I wish the Ruby maintainer in Ubuntu/Debian would just give up, this is a really really common problem and they don't know what they're doing.

NotShadowStar
Sep 20, 2000
I hated the Pickaxe. It reads like a Java refugee's first trip with Ruby, and in reality that's exactly what it is. Dave Thomas used to be a Java dude and discovered Ruby, so you see this weird Java-Rubyish naming convention and Java style programming.

The Ruby Programming Language co-written by Matz points out the differences between 1.8 and 1.9 where applicable. That book is good for a reference instead of learning. There really isn't THAT big of a difference between 1.8 and 1.9 if you're doing pure Ruby. I suggest just doing what you always do using 1.9, then consult the RPL book if things go wrong.

NotShadowStar
Sep 20, 2000
Which direction are you wanting to go, pulling from facebook to blog or from blog to facebook?

NotShadowStar
Sep 20, 2000
In essence you can copy Rails into the project instead of relying on system-installed Rails. It's good for keeping things static.

Is this a public server? I'd be scared running 1.x of Rails because of the litany of vulnerabilities that have sprung up since then.

NotShadowStar
Sep 20, 2000
Could try pinging localhost from the command line, but yeah some wireless 'management programs' gently caress with the network settings and break normal stuff.

Also, that tutorial is 2.5 years old and likely very, very wrong just by reading the blurb. I don't have an IBM account but a huge number of things have changed since 1.2. We're almost at 3.0. If you're really interested in Rails, use The Book.

NotShadowStar
Sep 20, 2000
The helper is exactly right. Models are strictly for data, the further you go down the route of your model doing view stuff the harder everything is going to be on you later. You also don't want convoluted logic in your view because in a couple months you are going to go :wtc: trying to figure out your view.

But after looking at it a bit and whipping something up something seems really off. Why do you want to create a new record if there is some condition on an existing model instance?

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

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.

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

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?

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.

Adbot
ADBOT LOVES YOU

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

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