Another HABTM Question


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
’ )
@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


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
’ )
@posting.body = body_content

@posting.categories = cats!

… omitted


  • Byron