HABTM for Dummies Question

Taking time off from programming is always painful :-).

I have the following Models:

====
class Tag < ActiveRecord::Base
has_and_belongs_to_many :problems
end

class Problem < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :tags
end

And the following migrations:

====
create_table “problems” do |t|
t.column “user_id”, :integer
t.column “title”, :string
t.column “description”, :text
t.column “created_at”, :datetime
t.column “updated_at”, :datetime
end
create_table “tags” do |t|
t.column “name”, :string
t.column “created_at”, :datetime
t.column “updated_at”, :datetime
end
create_table “problems_tags” do |t|
t.column “problem_id”, :integer
t.column “tag_id”, :integer
end

Now, from the console I do the following:

====
problem = Problem.find(1)
problem.tags.create :name => “test this tag”

The problem is that a row is added to the Tags table but nothing is
added to the problems_tags table. What am I doing wrong?

I hate being rusty. I can’t seem to find the answer anywhere. I am
sure it is really simple.

Thanks for all your help.

John K.
http://www.kopanas.com

============================================================
http://www.soen.info - Index of online software engineering knowledge
http://www.cusec.net - Canadian University Software Engineering
Conference
http://www.soenlive.com - Presentations from CUSEC

John K. wrote:

====
class Tag < ActiveRecord::Base
has_and_belongs_to_many :problems
end

class Problem < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :tags
end

====
problem = Problem.find(1)
problem.tags.create :name => “test this tag”

The problem is that a row is added to the Tags table but nothing is
added to the problems_tags table. What am I doing wrong?

The problem is that create() is not a supported method for HABTM
associations. Or at least there is some confusion about it. It’s not
listed in the API for HABTM, but it’s implemented in a broken way. What
you’re seeing is exactly what I saw when I dug into it last week.

Meanwhile, you can always do:

problem.tags << Tag.create(:name => “test this tag”)


Josh S.
http://blog.hasmanythrough.com

Thanks a million… that worked great.

Is the way you showed me though:

problem.tags << Tag.create(:name => “test this tag”

the “best practice” or is there another method that people recommend?

On 23-May-06, at 7:35 PM, Josh S. wrote:

====
associations. Or at least there is some confusion about it. It’s not
http://blog.hasmanythrough.com


Posted via http://www.ruby-forum.com/.


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails

John K.
http://www.kopanas.com

============================================================
http://www.soen.info - Index of online software engineering knowledge
http://www.cusec.net - Canadian University Software Engineering
Conference
http://www.soenlive.com - Presentations from CUSEC