0

First of all, I am totally new to rails.. I started to hack a rest Api together with the goal to consume it with ember-cli. I have 2 entities, books and authors.

I use the has_and_belongs_to_many relationship. Exactly like this

I can save books and authors. - I can consume my API with /books and /authors In addition, if I print book.authors it prints the authors. However, the foreign key are not included. The response looks like this:

{"id":1,"title":"the kite runner","created_at":"2015-06-06T08:45:13.000Z","updated_at":"2015-06-06T08:45:13.000Z"}

What I need is something like this:

{"id":1,"title":"the kite runner", author_ids: [1,3],"created_at":"2015-06-06T08:45:13.000Z","updated_at":"2015-06-06T08:45:13.000Z"}

I think its import to mention that i am using grape. grape-entity might be helpful.

desc "Return list of recent books"
get do
  Book.all
end
  • In HABTM relations, there should be a third table, in your case authors_books. This third table is a link between books and authors. – maicher Jun 06 '15 at 10:24
  • I have that. As I said, the relationship works. I need to know how can I search Book.find(1) and it return the book like this: `{"id":1,"title":"the kite runner", author_ids: [1,3],"created_at":"2015-06-06T08:45:13.000Z","updated_at":"2015-06-06T08:45:13.000Z"}` – user3407525 Jun 06 '15 at 10:29
  • The forign_key is not included because it does not belong to the model. You will need to tell rails to include those extra details in your controller, which we'll need to see before we can help more. – BroiSatse Jun 06 '15 at 11:00
  • so far i dont have any controller, except the application_controller. – user3407525 Jun 06 '15 at 11:39

0 Answers0