Noob issue with virtual attributes

Hello,
I have 2 models, city and tip. A city an have only one tip. So what i am
trying to do is to add my tip properties to the city form and create or
update the city with his child the tip.
but what i’ve done so far isn’t working… I have this error: undefined
method `build’ for nil:NilClass

Model City:
class City < ActiveRecord::Base
attr_accessible :name, :continent, :tip_attribute

has_one :shop
belongs_to :city_preferences
belongs_to :tip

validates_presence_of :name,:continent
def tip_attribute
tip
end

def tip_attribute=(attribute)
tip.build(attribute)
end

end

City form view:
<% form_for @city do |f| %>
<%= f.error_messages %>

<%= f.label :name %>
<%= f.text_field :name %>

<%= f.label :continent %>
<%= f.text_field :continent %>

<%= f.label :Tip %>

<%fields_for "city[tip_attribute]", @city.tip do |t| %>

Min <%= t.text_field :min %>

Max <%= t.text_field :max %> <%end%>

<%= f.submit "Submit" %>

<% end %>

Greg

On Mar 9, 6:31 am, Greg Ma [email protected] wrote:

Hello,
I have 2 models, city and tip. A city an have only one tip. So what i am
trying to do is to add my tip properties to the city form and create or
update the city with his child the tip.
but what i’ve done so far isn’t working… I have this error: undefined
method `build’ for nil:NilClass

def tip_attribute=(attribute)
tip.build(attribute)
end

If you have a has_many you can do tips.build(…) but with belongs_to
and has_one you need to call build_tip instead

Fred

Frederick C. wrote:

If you have a has_many you can do tips.build(…) but with belongs_to
and has_one you need to call build_tip instead

Fred

Thanks Fred, it works better now. But an have another issue. Now the
data are stored in the database but the column city_it in the table tips
is nil.
Do i have the set it the setter like this?

def tip_attribute=(attribute)
attribute[:city_id] = self.id
build_tip(attribute)
end

Tip model:
class Tip < ActiveRecord::Base
attr_accessible :min,:max,:city_id

has_one :city

validates_numericality_of :min, :only_integer => true
validates_numericality_of :max, :only_integer => true
end

It does work if I do this, but is it the correct way to do it? should it
be filled automaticly by active record?

Greg