How to deal with this code ?

Hi,everyone
  Here is my model code--->

fireflyman wrote:

Hi,everyone
  Here is my model code--->
------------------------------------------------------------------------
  has_many :authors_books
  has_many :authors, :through => :authors_books

  belongs_to :book
  belongs_to :author

has_many :authors_books
  has_many :books, :through => :authors_books
---------------------------------------------------------------------------

I wonder... Try adding "belongs_to :author" and "belongs_to :book" and
try again.

Hi --

On 8 Sep 2009, at 13:44, David A. B

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When I run my test,and goes wrong .Like this--->
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1) Error:
test_ferret(BookTest):
ActiveRecord::HasManyThroughCantAssociateNewRecords: Cannot associate
new record
s through 'Book#authors_books' on '#'. Both records must have an id
in
order to
create the has_many :through record associating them.

Just looking at it quickly I suspect that it's because you're trying
to add an Author to an unsaved Book record, and that it's impossible
for the system to add a row to authors_books because it doesn't have
the necessary information (since unsaved records don't have id's).

Rails 2.1 (or was it 2.2?) made has many through a lot more sane in
that respect.

Fred

So,Could you help me deal with my code ?

David already gave you the answer, you are trying to add a
has_many :through associated record to an unsaved record. The error
message is pretty much telling you that "Cannot associate
new records through 'Book#authors_books' on '#'. Both records must
have an id in order to create the has_many :through record associating
them.". The association is made through the author_books table with
the id of both, the author and the book. With the book id being nil...
I think you get the point.

If you use Book.new (and thats what you are doing in your test), the
new books id is still nil because it hasn't been saved to the database
yet. Replace Book.create and you should be fine (as long as your
validations don't fail).

-- pascal

> So,Could you help me deal with my code ?

David already gave you the answer, you are trying to add a
has_many :through associated record to an unsaved record. The error
message is pretty much telling you that "Cannot associate
new records through 'Book#authors_books' on '#'. Both records must
have an id in order to create the has_many :through record associating
them.". The association is made through the author_books table with
the id of both, the author and the book. With the book id being nil...
I think you get the point.

Or upgrade to a version of rails that doesn't require this.

Fred