Can someone help me understand this? I have a habtm between Books and
Authors. In my books form, I added a form field that is a bunch of
check boxes with a list of authors, where they are named like:
name=''authors_books["author_id"][id of this author]''
I added the following function to my Books model:
def authors=( authors_form_hsh )
self.authors.each{ |aa| self.authors.delete( aa ) }
authors_form_hsh.each_key{ |key| self.authors << Author.find( key
) }
end
And in my books controller:
def create
@book = Book.new(@params[:book])
@book.authors =
@params["authors_books"]["author_id"] # <--
I added this to the scaffold
if @book.save
flash[''notice''] = ''Book was successfully
created.''
redirect_to :action => ''list''
else
render_action ''new''
end
end
So, I am passing the hash to authors=(), and for every key in that
hash(the author id''s), I add a relationship.
It seems to be working, *but*, my log shows me something that has me
concerned: (i''ve snipped some of the content to make the log shorter)
Processing BooksController#create (for 128.249.153.72 at Tue Jun 14
15:07:41 MST 2005)
Parameters:
{"authors_books"=>{"author_id"=>{"1"=>"",
"2"=>""}},
"submit"=>"Create",
"action"=>"create",
"controller"=>"books",
"book"=>{"date(1i)"=>"2005",
"date(2i)"=>"6", "title"=>"Test
Book6",
"date(3i)"=>"14",
"series_index"=>"37", "cover"=>"",
"about"=>"testing, 123",
"publisher"=>"blah",
"series_id"=>"2"}}
Book Columns (0.001261) SHOW FIELDS FROM books
Book Columns (0.001186) SHOW FIELDS FROM books
{"1"=>"", "2"=>""}
Author Load (0.001013) SELECT * FROM authors WHERE authors.id =
''1'' LIMIT 1
SQL (0.000245) BEGIN
Author Columns (0.001011) SHOW FIELDS FROM authors
SQL (0.000237) COMMIT
Author Load (0.000892) SELECT * FROM authors WHERE authors.id =
''2'' LIMIT 1
SQL (0.000240) BEGIN
SQL (0.000171) COMMIT
SQL (0.000183) BEGIN
SQL (0.000596) INSERT INTO books (`title`, `date`, `series_index`,
`cover`, `about`, `publisher`, `series_id`) VALUES(''Test
Book6'',
''2005-06-14'', 37, '''', ''testing,
123'', ''blah'', 2)
Author Update (0.000736) UPDATE authors SET (*snip* every field is
updated, but with apparently the same content) WHERE id = 1
authors_books Columns (0.000957) SHOW FIELDS FROM authors_books
SQL (0.000409) INSERT INTO authors_books (`author_id`, `book_id`)
VALUES (''1'', ''171'')
Author Update (0.000583) UPDATE authors SET (*snip* every field is
updated, but with apparently the same content) WHERE id = 2
authors_books Columns (0.000939) SHOW FIELDS FROM authors_books
SQL (0.000403) INSERT INTO authors_books (`author_id`, `book_id`)
VALUES (''2'', ''171'')
SQL (0.000255) COMMIT
The statements that have me concerned are the "UPDATE authors SET"
statements. All I have done (or so I thought), was create a new book
and added an entry in the authors_books table. Why on earth are both
of the authors being "updated" (these are the 2 authors of this book)?
Their content should not be changing. Did I do something wrong?
Matt