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
On 2/14/06, Dave Hoefler <dhoefler@gmail.com>
wrote:>
> 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 Hoefler
>
> There really needs to be a ''Rails on Relationships'' book
for us geeks ;-)
> _______________________________________________
> Rails mailing list
> Rails@lists.rubyonrails.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
>
--
Byron
http://byron.saltysiak.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL:
http://wrath.rubyonrails.org/pipermail/rails/attachments/20060214/4c85a4f1/attachment.html