Model Attributes

I’m having trouble with a model:

class Job < ActiveRecord::Base
belongs_to :company
belongs_to :city
belongs_to :region
belongs_to :country
belongs_to :department
belongs_to :user

has_many :comments

accepts_nested_attributes_for :city, :allow_destroy => :false
accepts_nested_attributes_for :region, :allow_destroy => :false
accepts_nested_attributes_for :country, :allow_destroy => :false
accepts_nested_attributes_for :company, :allow_destroy => :false
accepts_nested_attributes_for :department, :allow_destroy => :false
end

I’m trying to create a form with nested attributes but whenever I call
@job.city.build it complains that @job.city is nil.

You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.build

Here is the associated controller code:

def new
@job = Job.new

@job.city.build
@job.region.build
@job.counrty.build
@job.department.build
@job.company.build

end

It would appear that I am wrong in my assumption that the relation in
the model allows me to treat city as an attribute. How would I go
about making this work?

On Aug 22, 6:22 pm, Glen [email protected] wrote:

I’m having trouble with a model:
def new
@job = Job.new

            @job.city.build
            @job.region.build
            @job.counrty.build
            @job.department.build
            @job.company.build

The magically created methods are @job.build_city etc.

Fred

On Aug 22, 3:20 pm, Frederick C. [email protected]
wrote:

            @job.company.build

The magically created methods are @job.build_city etc.

Thank you much, that did the trick.

Fred’s got the answer on this one, but holy database normalization
Batman! A ‘country’ string field is enough for most people…

–Matt J.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs