1

I am new to rails and I have two models, one has a foreign key on the other model.

I created a controller and defined and index method which is working fine:

  def index
    @collections = Collection.all
    render json: @collections 
  end

Which is rendering something like this:

[{"id":1,"title":"Collection A","book_id":1,"created_at":"2016-04-10T18:41:32.709Z","updated_at":"2016-04-10T18:41:32.709Z"}]

I would like to transform that book_id field into a list of book objects, something like this:

[{"id":1,"title":"Collection A","books": [{"book_id": 1, "title: "book_title"},],"created_at":"2016-04-10T18:41:32.709Z","updated_at":"2016-04-10T18:41:32.709Z"}]

Then I tried with:

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

But is giving me syntax error and I cannot see how to do it properly in this doc http://guides.rubyonrails.org/layouts_and_rendering.html

I am using Rails 4.1.0

1 Answer 1

2

Try:

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

or if you would like just the :id and :title:

  def index
    @collections = Collection.all
    render :json => @collections.as_json(
                  :include => {:book => {:only => [:id, :title]}}
                )
  end
Sign up to request clarification or add additional context in comments.

7 Comments

I tried your first example and it tells me undefined local variable or method `collections' for #<CollectionsController:0x00000003d73680> Did you mean? @collections Then I tried with @collections and it says Did you mean book_id?
Let me fix my answer
Hello! with @collections it gives me this error: undefined method `book' for #<Collection:0x00000002df23a0> Did you mean? book_id
Don't you have belongs_to :book into your Collection class?
mmm I dont quite understand you, I am new to rails, I created the models this way: bin/rails generate model Book title:string plot:text, bin/rails generate model Collection title:string plot:text book_id:integer
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.