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!