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:
c = Category.find(1)
t = Topic.new :name => "Test", :category => c
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:
t = Topic.new :name => "Test", :category_id => c
Another way do do it which can be a bit nicer:
t = c.topics.build(:name => "Test") # Builds an object without saving
t = c.topics.create(:name => "Test") # Builds an object and saves it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With