This project is archived and is in readonly mode.

#3043 ✓stale
Paul Hinze

has_one :through not working with new_record, breaks validation

Reported by Paul Hinze | August 12th, 2009 @ 04:09 PM

I believe that when a through association is set, even if the record hasn't yet been saved, that the setters and getters on the instance's association should still work as expected.

Given the following models:

class User < ActiveRecord::Base
  has_many :accounts

class Account < ActiveRecord::Base
  belongs_to :user
  has_many   :orders

class Order < ActiveRecord::Base
  belongs_to :account
  has_one    :user,   :through => :account

We happily move along setting up a new object:

>> o =
=> #<Order id: nil, ... >
>> o.account = Account.first
=> #<Account id: 12345, ... >
>> o.account.user
=> #<User id: 23456, ... >
>> o.user
=> nil

But that last doesn't make sense... if o.account.user is available it seams reasonable to expect that o.user would be readily accessible, but it is not.

This has implications in validation, too. Say I wanted to this validation on my order:

class Order < ActiveRecord::Base
  validates_presence_of :user

Because the instance o cannot 'see' the user without being saved, and it cannot be saved without the validation passing, you have a validation rule that will never pass.

So it's possible that rails just "isn't supposed to work this way", but I think the examples I've given make for fairly reasonable expected functionality.

I've attached a couple of test cases that fail on 2-3-stable and master that I believe express the behavior I'm describing here.

I'm happy to hack up a patch to make this work, but first I'd like confirmation that this is behavior that rails should have.

Assigning to Michael since he was the name that came up in #1749, which also had to do with has_one :through.

Thanks for your time!

Comments and changes to this ticket

  • Rohit Arondekar

    Rohit Arondekar October 6th, 2010 @ 06:46 AM

    • State changed from “new” to “stale”
    • Importance changed from “” to “”

    Marking ticket as stale. If this is still an issue please leave a comment with suggested changes, creating a patch with tests, rebasing an existing patch or just confirming the issue on a latest release or master/branches.

  • Ryan Bigg

    Ryan Bigg October 11th, 2010 @ 10:58 AM

    • Tag cleared.

    Automatic cleanup of spam.

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href=""></a>