Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

has_one :through not working with new_record, breaks validation

#3043

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
end

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

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

We happily move along setting up a new object:

>> o = Order.new
=> #<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 has_one :through not working?, which also had to do with has_one :through.

Thanks for your time!

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

State: stale
Milestone: none
Assigned to: Michael Koziarski Michael Koziarski
Importance: none

Activity

  1. Rohit Arondekar
    Rohit Arondekar
    • 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.

    October 6th, 2010 @ 06:46 AM

  2. Ryan Bigg
    Ryan Bigg
    • Tag cleared.

    Automatic cleanup of spam.

    October 11th, 2010 @ 10:58 AM