Postback issue

Hello, I am attempting to implement the "Clean Up Controllers with
Postback Actions" Rails Recipe and I am having a problem with it.

First, the code:

I tested it this morning in ./script/console:

pt = ProductType.find( :first )

=> #<ProductType:0x253b410 @attributes={"name"=>"Poster", "id"=>"1"}>

ProductType.find_by_id( nil )

=> nil

p = ProductType.new

=> #<ProductType:0x2535150 @attributes={"name"=>nil}, @new_record=true>

p.name = "Yahar"

=> "Yahar"

p.save!

=> true

ProductType.find_by_id( nil )

=> #<ProductType:0x25230f4 @attributes={"name"=>"Yahar", "id"=>"5"}>

So evidently if you find_by_id( nil ), it returns the last object
created? That sort of breaks the recipe in that it populates the form
when you immediately return to the page.

Essentially, I take it that I have to explicitly check for the
existence of params[:id] which muddies the code a bit.

Hi,

I tested it this morning in ./script/console:

So evidently if you find_by_id( nil ), it returns the last object
created? That sort of breaks the recipe in that it populates the form
when you immediately return to the page.

Essentially, I take it that I have to explicitly check for the
existence of params[:id] which muddies the code a bit.

I'm guessing that you're using MySQL? Try this in MySQL itself:

        CREATE TABLE foo (id INT(11) NOT NULL AUTO_INCREMENT,
                                 name VARCHAR(255),
                                 PRIMARY KEY(id));
        
        INSERT INTO foo (name) VALUES("Tada");
        SELECT * FROM foo WHERE id IS NULL;
        SELECT * FROM foo WHERE id IS NULL;

The first SELECT will return the record you just inserted. The second
select returns the empty set, as should be expected.

Seems to be a problem on tables that have an AUTO_INCREMENT field. It
doesn't seem to matter whether the table is MyISAM or InnoDB. I
recently got bit by this when two users created their accounts nearly
simultaneously and the second one got the first ones profile.

Not nice.

This does not happen in Postgres, btw.

Rick Tessner

Transactions don't help this?

Wow. I suppose I can test for empty params[:id] first, but that both
makes the code a bit longer and more importantly means I am writing
code to compensate for a specific database implementation.

Did you solve the problem similarly?

Hi,

Transactions don't help this?

Nope, transactions do not seem to help either. It's not a good thing
since the identical query twice in a row, with no other changes to the
DB, yield different results.

Is this expected behavior (a 'feature')?

Rick Tessner wrote:

Hi,

Hmm, I have used postgres in the past but I recall its clustering
capabilities at the time seemed rather limiting. I'll have a look
again.

Anyway, thanks a lot for clarifying this for me. I really appreciate
it.

Best regards.