Forum: Ruby on Rails Another HABTM Question

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and 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

class Posting < ActiveRecord::Base
  has_and_belongs_to_many :categories

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

def create
	@posting =[:posting])
	body_content = @posting.body
	body_content.gsub!( /(.*)(\n)/, '\1<br />' )
	@posting.body = body_content!
	@posting.user_id = session[:user_id]
	logger.debug("Saving the post.")
	  flash[:notice] = 'Posting was successfully created.'
	  redirect_to :controller => 'list', :action => 'index'
	  render :action => 'new'

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 and the 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
which the new posting should be related:

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

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

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