1
votes

I have two models, Collection and Book. A book belongs to a Collection and a Collection has many Books.

I have generated my models this way:

bin/rails generate model Collection title:string plot:text
bin/rails generate model Book title:string plot:text Collection:references

Then it generates these models:

class Book < ActiveRecord::Base
  belongs_to :Collection
end

class Collection < ActiveRecord::Base
end

So I have read in other answers like this one has_many, belongs_to relation in active record migration rails 4 I have to manually add the has_many field in the Collection model.

Ok then it looks like this:

class Collection < ActiveRecord::Base
  has_many :books
end

And then I run the migration:

bin/rake db:migrate

Then I add some data, a couple of books and a collection with (I am not sure if the collection post is correct):

curl -H 'Content-Type: application/json' -X POST -d '{"title" : "Book 1", "plot" : "book"}' http://127.0.0.1:3000/books
curl -H 'Content-Type: application/json' -X POST -d '{"title" : "Book 2", "plot" : "book"}' http://127.0.0.1:3000/books
curl -H 'Content-Type: application/json' -X POST -d '{"title" : "Collection", "plot" : "collection", "book_id" : [1,2]}' http://127.0.0.1:3000/collections

Then I check them in http://127.0.0.1:3000/collections and it crashes

  def index
    @collections = Collection.all
    render :json => @collections.as_json(
                  :include => :book
                )
  end

It says

undefined method `book' for # Did you mean? books books=

If I try that and replace book with books then the books list is empty:

[{"id":1,"title":"Collection","plot":"collection","created_at":"2016-04-11T17:53:38.892Z","updated_at":"2016-04-11T17:53:38.892Z","books":[]}]

This is my create method:

  def create
    @collection = Collection.new(collection_params)

    @collection.save
    redirect_to @collection
  end

  private
    def collection_params
      params.permit(:title, :plot, :book_id)
    end

Shouldnt it store the book inside collection? Why is not appearing in the index view?

1

1 Answers

2
votes

You would want collection_id to live on the books table if books belong to collections then when creating the data you would want to do it as:

curl -H 'Content-Type: application/json' -X POST -d '{
  "title" : "Collection", 
  "plot" : "collection"}' 
http://127.0.0.1:3000/collections

curl -H 'Content-Type: application/json' -X POST -d '{
  "title" : "Book 1", 
  "plot" : "book", 
  "collection_id": "1"}' 
http://127.0.0.1:3000/books

curl -H 'Content-Type: application/json' -X POST -d '{
  "title" : "Book 2", 
  "plot" : "book", 
  "collection_id": "1"}' 
http://127.0.0.1:3000/books