I currently have 2 models setup:
class Topic < ActiveRecord::Base
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :topics
end
I am now trying to create a topic with a category associated in the rails console:
t = Topic.new :name => "Test", :category => Category.find(1)
Trouble is the model has category_id, and so I’d need to use:
c = Category.find(1)
t = Topic.new :name => "Test", :category_id => c.id
But, I’ve seen many times the ability to simply use :category instead of :category_id and pass in the category object instead of the objects id. Where am I going wrong?
When I do:
c = Category.find(1)
t = Topic.new :name => "Test", :category => c
I receive:
ActiveRecord::UnknownAttributeError: unknown attribute: category
You should be able to just do this:
The association definition on the model is what lets you do this.
Interesting note, you can use :category_id and still just pass in the object, it will get the ID for you:
Another way do do it which can be a bit nicer: