Re: How do I create a form for "has_and_belongs_to_many" association?

1,508 views
Skip to first unread message

masta Blasta

unread,
Jul 31, 2012, 3:05:07 PM7/31/12
to rubyonra...@googlegroups.com
Vincent Lin wrote in post #1070656:
> git://github.com/vincentopensourcetaiwan/vocabulary.git
> This is my source codes.
>
> I got two models, Book and Word.
>
> class Book < ActiveRecord::Base
> has_and_belongs_to_many :words
> end
>
> class Word < ActiveRecord::Base
> has_and_belongs_to_many :books
> end
>
> I got a Join Tables for has_and_belongs_to_many Associations
>
> class CreateBooksWords < ActiveRecord::Migration
> def self.up
> create_table :books_words, :id => false do |t|
> t.integer :book_id
> t.integer :word_id
>
> t.timestamps
> end
> end
>
> def self.down
> drop_table :books_words
> end
> end
>
> Now I want to create a form, and user can insert words into a book.
> How do I do that?

There are some conceptual issues here.
If this is in fact a many-to-many relationship between books and words
so that, a book can have many words, and a word can be in many books,
then:

Don't think of "i want to add words to a book", but think of "I have a
word, and i have a book, and i want to build a relationship between the
two."
So the form you're talking about is not a form on words and books, but a
form about a single model: book_word_relationship (name it whatever you
like). You will have a relationship_controller which will handle #create
and #destroy actions. At this point the form should be trivial. The
#create action will take as parameters the book_id and word_id. Or more
appropriately @book.book_word_relationships.build(params[:word).

This means you will need a proper model and controller to handle these
relationships. Which also means that a HABTM relationship is not
appropriate and you should use has_many :through=>'relationship'.

This railscast has some good advice about the front-end of a many-many
relationship:
http://railscasts.com/episodes/163-self-referential-association
don't worry about the self-referential part.

--
Posted via http://www.ruby-forum.com/.

Weston Platter

unread,
Aug 2, 2012, 11:48:06 AM8/2/12
to rubyonra...@googlegroups.com
It sounds like the question has been sufficiently answered.

But if you are looking for more content on the subject, check out the Rails Guides on Associations.
Reply all
Reply to author
Forward
0 new messages