Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

has_and_belongs_to_many assocation is not working

I have a problem with a has_and_belongs_to_many association in my Ruby On Rails project.

Here are my models:

class Store < ActiveRecord::Base
  attr_accessible :address, :city, :map_url, :name, :uimage_url
  has_and_belongs_to_many  :furnitures_id
end

class Furniture < ActiveRecord::Base
  attr_accessible :description, :image_url, :maintenance, :name, :size
  has_and_belongs_to_many  :store_id
end

This is my join table migration:

create_table "furnitures_stores", :id => false, :force => true do |t|
  t.integer "furniture_id"
  t.integer "store_id"
end

I then tried to insert some values with seed.rb:

Furniture.delete_all
furnitures =  Furniture.create([{name: 'aaaa 1'}])

Store.delete_all
storee =  Store.create([{name: 'S 1'}])

But it doesn't work; I have this error:

**rake aborted!
uninitialized constant Store::FurnituresId**
like image 738
Teo Avatar asked Jun 12 '13 17:06

Teo


People also ask

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is a polymorphic association in rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.


1 Answers

You need has_and_belongs_to_many :furnitures and has_and_belongs_to_many :stores. You need to refer to the model, not the foreign key.

See A Guide to ActiveRecord Associations for more information.

like image 200
Michael Lawrie Avatar answered Sep 19 '22 08:09

Michael Lawrie