Hi --

On Mon, 7 Sep 2009, 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 use the authors_books to associate book and author.
>
> And then ,I write a unit test,book_test.rb---->the code like follow
>
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> def test_ferret
> Book.rebuild_index
>
> assert Book.find_with_ferret("Pride and Prejudice")
> assert_difference Book, :count do
>  book = Book.new(:title => 'The Success of Open Source',
>                           :published_at => Time.now, :page_count =>
> 500,
>                           :price => 59.99, :isbn => '0-647-01292-5')
>  book.authors << Author.create(:first_name => "Steven", :last_name =>
> "Weber")
>  book.publisher = Publisher.find(1)
>  assert book.valid?
>  book.save
>
>  assert_equal 1, Book.find_with_ferret("Open Source").size
>  assert_equal 1,Book.find_with_ferret("Steven Weber").size
>   end
> end
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> 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).


David

-- 
David A. Black / Ruby Power and Light, LLC / http://www.rubypal.com
Ruby/Rails training, mentoring, consulting, code-review
Latest book: The Well-Grounded Rubyist (http://www.manning.com/black2)

September Ruby training in NJ has been POSTPONED. Details to follow.

--~--~---------~--~----~------------~-------~--~----~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to