0

This is my first Rails project and this seems like a very simple issue, but I can't seem to find any examples.

I don't know how to create an object and set it to be a child of another already existing object. In this case I have a City and a Country, and I don't know how to create a new City and set it to be related to a certain Country (which is already in my database).

Class City < ActiveRecord::Base
   attr_accessible #nothing
   belongs_to :country
end

Class Country < ActiveRecord::Base
   attr_accessible #nothing
   has_many :cities
end

When I create a new Country object and a new City object in a rake task, how should I associate the two objects?

Right now the closest thing I can find to what I want to do is:

city = City.new
city.name = "Chicago"
country = Country.find(1)
city_final = country.cities.create(city.attributes)
city_final.save

The two problems I have with this code are that I don't want to use mass-assignment (I plan on having both of these models' CRUD operations available to rake tasks only), and I'm not sure how it works. Assuming I had mass-assignment completely open, would this code create a duplicate city object? Because otherwise why would I need to pass in the city's attributes? It seems like what I'm looking for is some way to add a new city to the country's cities attribute by direct assignment, without going through the controller.

I've looked at the RoR ActiveRecord Relationships doc page (http://guides.rubyonrails.org/association_basics.html), but I'm not able to figure this out.

Thanks a bunch for any help!

jhonsmc
  • 23
  • 8

1 Answers1

0

ActiveRecord gives you some getter and setter methods for collections, see http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Auto-generated+methods

So you could write

country = Country.find(1)
city = City.new
city.name = "Chicago"
city.country = country #Or Country.find(1) directly here
city.save

Hope it works as you want it to!

Jakob W
  • 3,347
  • 19
  • 27