Forum: Ruby on Rails making a new join in a habtm relationship

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.
73c04e9ef9ca435c5b19a2e765ae6d20?d=identicon&s=25 Max Williams (max-williams)
on 2007-07-26 14:04
I have a class (Article) that has a habtm relationship with 'links',
where links are also Articles.  I've got a join table called
articles_links, and have set up the relationship so that it understands
what's going on (i think):

   1. class Article < ActiveRecord::Base
   2.   has_and_belongs_to_many :links,
   3.     :class_name => "Article",
   4.     :association_foreign_key => "link_id",
   5.     :join_table => "articles_links"

When i make a new link, using a form, the article is created fine but i
can't work out how to create the join.  I'm sure this is simple but i
can't find out how.  My 'create link' method looks like this:

   1. def create_link
   2.     @link =[:article])
   3.     #set some attributes of the new object
   4.     if @link.title == ""
   5.       @link.title =
   6.     end
   7.     @link.added_at =
   8.     @link.user_id = session[:user].id
   9.     @link.points = 0
  10.     #then save it and return to the original article page
  11.     if
  12.       flash[:notice] = 'Link was successfully created.'
  13.       redirect_to :action => 'show', :id => params[:article].id
  14.     else
  15.       flash[:warning] = 'Could not create link'
  16.       render :action => 'new_link'
  17.     end
  18. end

Can anyone explain to me how to set up the join properly?
This topic is locked and can not be replied to.