Question

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'
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top