Ruby on Rails
Friday, January 24, 2014
On 1/24/14, 11:25 AM, Martin Sloan wrote:
Hello,
I'm new to Ruby/Rails and going through 'Beginning Rails 4'. In chapter 6 it has me create a join table for an articles and categories table (articles_categories). In the migrate file I've entered this code from the book:
class CreateArticlesCategories < ActiveRecord::Migrationdef changecreate_table :articles_categories, :id=> false do |t|t.references :articlet.references :categoryendenddef self.downdrop_table :articles_categoriesendend
My issue is that after I migrate this file, when I try to make an association between the article and category object (article.categories << category) it spits an error that article_id does not exist in articles_categories table. It makes sense to me since the references above do no have _id appended in the class. If I change the class to the following, creating the relationship between article and category works fine:
class CreateArticlesCategories < ActiveRecord::Migrationdef changecreate_table :articles_categories, :id=> false do |t|t.integer :article_idt.integer :category_idendenddef self.downdrop_table :articles_categoriesendend
My question is, how can I get the 't.references' format to work so that AR looks for an 'articles' and 'categories' column, instead of the same with _id appended?
You need to use has_many :through when working with join tables, not has_and_belongs_to_many. The :through parameter specifies the join table.
See this section of the Rails guide: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
--
- Blaine LaFreniere
- Phone: 801-448-6124
- E-mail: brlafreniere@gmail.com
- Web: brlafreniere.com
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment