0

this seems like a re-occuring problem for my (probably conceptually), hopefully I can tackle it this time! #stillLearning

Two models. A Collection has_many :examples A Example belongs_to :collection

Collection has a title: string Example has collection_id: integer, and a description: text

Inside my collection/show, I want to also be able to add an Example via this simple form:

<%= form_for(@example) do |e| %>

    <h3><%= e.label :description %></h3>
    <%= e.text_area :description %>
    <%= e.submit %>

<% end %>

But I get a NoMethodError...

undefined method `description' for #<Collection:0x007fe3c4087898>. 

I understand that @collection doesn't have :description, so that means I have to create a link between Collection and Example right?

Assuming my guess is correct, I tried:

rails g migration AddExampleRefToCollections example:references

but got the following error:

SQLite3::SQLException: near "references": syntax error: ALTER TABLE "collections" ADD "example" references/Users/davidngo/.rvm/gems/ruby-1.9.3-p429/gems/sqlite3-1.3.8/lib/sqlite3/database.rb:91:in `initialize'
vee
  • 36,569
  • 5
  • 65
  • 72
dngoo
  • 479
  • 1
  • 5
  • 16
  • Have a look at the answer here: http://stackoverflow.com/questions/4954969/rails-3-migrations-adding-reference-column – vee Aug 18 '13 at 23:49
  • Thanks for fixing the formatting of my post. Still learning the proper etiquette! – dngoo Aug 19 '13 at 14:34

1 Answers1

1

If Collection has many Examples then Example should be the one referencing Collection by id in the database:

rails g migration AddCollectionIdToExamples collection_id:integer

In CollectionsController#show, make sure you are instancing a new empty example to use in the form you are going to use:

def show
  #stuff
  @example = @collection.examples.new
akhanubis
  • 3,956
  • 1
  • 24
  • 19
  • Thank you @PabloB. This allowed my form to display in CollectionsController#show. But now, when I click "create" example, it couldn't find the Collection id in the ExamplesController#create method. How do I link up the collection_id to the example when it's not automatically part of the parameters? – dngoo Aug 19 '13 at 14:31
  • The above bug was solved by this thread here: http://stackoverflow.com/questions/16138353/activerecordrecordnotfound-couldnt-find-without-an-id Essentially, the routes had to be nested so that collection_id was a part of the parameters. I now understand routing better! Yes! The feeling of progress! – dngoo Aug 19 '13 at 14:58