Problems with habtm

hi, i’m having some problems with habtm association, when i try to
list Empresas form a Category, i get the association ID instead of the
Empresa ID, i’m using sqlite3

paulo-geyers-macbook:100empresas paulo$ ./script/console
Loading development environment (Rails 2.3.4)

Category.find(:first).empresas.each {|e| puts e.id}
608
609
=> [#<Empresa id: 608, name: “Fast Shop”, description: nil,
created_at: “2009-09-09 17:55:49”, updated_at: “2009-09-09 17:55:49”>,
#<Empresa id: 609, name: “Livraria Cultura”, description: nil,
created_at: “2009-09-09 17:55:49”, updated_at: “2009-09-09 17:55:49”>]

Empresa.find(:all).each {|e| puts e.id}
54276017
1387109338
=> [#<Empresa id: 54276017, name: “Livraria Cultura”, description:
nil, created_at: “2009-09-09 17:55:49”, updated_at: “2009-09-09
17:55:49”>, #<Empresa id: 1387109338, name: “Fast Shop”, description:
nil, created_at: “2009-09-09 17:55:49”, updated_at: “2009-09-09
17:55:49”>]

here follows the model codes
empresa.rb
class Empresa < ActiveRecord::Base
has_and_belongs_to_many :categories, :foreign_key =>
‘empresa_id’, :association_foreign_key => ‘category_id’
validates_presence_of :name
acts_as_voteable
end

category.rb
class Category < ActiveRecord::Base
has_and_belongs_to_many :empresas, :foreign_key =>
‘category_id’, :association_foreign_key => ‘empresa_id’
validates_presence_of :name
end

i’ve tried to set the keys manually, but didn’t work too

thanks,
Paulo

it looks all wrong to me, and overconfigured too. check some
tutorials.

Category habtm :empresas
Empresa habtm :categories

CategoryEmpresa
belongs_to :category
belongs_to :empresa

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001836

i didn’t create the model CategoriesEmpresas, and the table had the
“id” field, that was the problem
just another case of someone trying to use the framework without
reading carefully the documentation

thanks Eric!

Paulo Geyer wrote:

i didn’t create the model CategoriesEmpresas,

You don’t need that if you’re using habtm. You only need the join model
if you’re using :through.

and the table had the
“id” field, that was the problem

Yes, that apparently gets in the way.

just another case of someone trying to use the framework without
reading carefully the documentation

:slight_smile:

thanks Eric!

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs