Another HABTM Question


#1

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


#2

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

@posting.categories = cats
@posting.save!

… omitted

end

  • Byron