Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSarah A. Morrigan
14,329 Pointscode challenge: missing key?
class BlogPost < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :blog_post_id
end
seems ok but it gives an error message.
so in the Comment schema each comment is indexed to blog_post_id key, but shouldn't there be another key other than blog_post_id in the BlogPost schema? I have no idea where "comments" key from the left-hand table fits in with the right-hand table in this setting.
1 Answer
Luigi Zhou
16,121 PointsThere is no missing key. Every BlogPost has many comments but a comment has only one blogpost. So when you search for how many comments a blog post has, you only have to search for how many comments have the id that identify the blog post that it belongs to. The code challenge asks you only to setup the relationship between two models, so in this case you don't have to worry about keys or anything else. So in blogPost you specify that it has many comments by writing "has_many :comments", and for comments you have to specify that it belongs to a blog post. In Ruby on Rails, when the model is written in CamelCase, it is references through his downcase name separated with underscore, so in this case you have to write "belongs_to :blog_post".
I'm sorry for my English if I made some mistake (I'm Italian) and I hope I was clear enough! If there's anything you didn't understand in my answer, feel free to ask!