Forum: Ruby on Rails Using an associated model in an attribute setter

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
399fc4b3a679b0c0fdadc203259d6bd2?d=identicon&s=25 Rainer Frey (Guest)
on 2008-10-22 07:22
(Received via mailing list)
Hi,
I want to use an associated model in an overwritten attribute write
method. But this fails on create, as the association is not yet
initialized. Code is:

class Forward < ActiveRecord::Base
  belongs_to :domain
  validates_presence_of :domain, :destination
  validates_uniqueness_of :name, :scope => :domain_id

  def destination=(dest)
      dest = dest + '@' + domain.name unless (domain.blank? || dest =~
/@/)
      write_attribute :destination, dest
  end
end

When calling destination= and then save, it works fine, put when
calling Forward.new(attributes) from the controller, domain yields nil
in destination=, even though domain is initialized before saving, and
validation succeeds.

How can I achieve that destination= is executed correctly when creating
a new Forward?
I tried the following callback in Forward:
  before_validation_on_create { |record|
record.destination=record.destination}
and it seems to work. Is this correct, or might this have some side
effects? It also seems quite hacky, is there a cleaner way?

Regards
Rainer Frey
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2008-10-23 04:37
(Received via mailing list)
On 21 Oct 2008, at 15:56, Rainer Frey wrote:

>
> validation succeeds.
>
> How can I achieve that destination= is executed correctly when
> creating
> a new Forward?

Forward.new(attributes) boils down to:
- create a blank instance
- attributes.each {|k,v| object.send("#{k}=",v)

hashes are unordered so you can't rely on domain being set before
destination is.

Fred
399fc4b3a679b0c0fdadc203259d6bd2?d=identicon&s=25 Rainer Frey (Guest)
on 2008-10-23 15:24
(Received via mailing list)
Frederick Cheung wrote:

> Forward.new(attributes) boils down to:
> - create a blank instance
> - attributes.each {|k,v| object.send("#{k}=",v)
>
> hashes are unordered so you can't rely on domain being set before
> destination is.

Ok, so I need to take care of this afterwards. Any comments on below
solution/workaround?

>> I tried the following callback in Forward:
>>  before_validation_on_create { |record|
>> record.destination=record.destination}
>> and it seems to work. Is this correct, or might this have some side
>> effects? It also seems quite hacky, is there a cleaner way?

Regards
Rainer Frey
This topic is locked and can not be replied to.