Ruby on Rails Tuesday, July 31, 2012

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/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment