Forum: Ruby on Rails Another HABTM Question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Dave H. (Guest)
on 2006-02-14 07:30
(Received via mailing list)
Hi there,

I have a question on what would be the best way to save a HABTM model.

A posting habtm categories, and a category habtm postings.

class Category < ActiveRecord::Base
     has_and_belongs_to_many :postings
end

class Posting < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

In my blog_controller, where the actual posting is saved, is where I
think I'm having some trouble. Here's what I currently have to save a
post:

def create
	@posting = Posting.new(params[:posting])
	body_content = @posting.body
	body_content.gsub!( /(.*)(\n)/, '\1<br />' )
	@posting.body = body_content

	@posting.save!
	@posting.user_id = session[:user_id]
	logger.debug("Saving the post.")
	if @posting.save
	  flash[:notice] = 'Posting was successfully created.'
	  redirect_to :controller => 'list', :action => 'index'
	else
	  render :action => 'new'
	end
end

I can successfully load all the categories into a multiple selection
box on the page that is creating the posting, but I'm unsure how to
save the posting.id and the category.id into the categories_postings
table within the 'create' action.

Thank you,
Dave H.

There really needs to be a 'Rails on Relationships' book for us geeks
;-)
Byron S. (Guest)
on 2006-02-14 07:39
(Received via mailing list)
To save a HABTM relationship you should just have to wire the objects
together correctly and then save either one of them.

So in your case it might be something like:

# let's say your create function will take in a list of category ids
with
which the new posting should be related:

def create(category_ids)
  cats = Category.find(category_ids)
  @posting = Posting.new(params[:posting])
  body_content = @posting.body
  body_content.gsub!( /(.*)(\n)/, '\1<br />' )
  @posting.body = body_content

  @posting.categories = cats
  @posting.save!
  # ... omitted
end


- Byron
This topic is locked and can not be replied to.