user1908375
user1908375

Reputation: 1089

Nested routes not working as expected

I am creating an API with rails5.beta, I followed the guide to create nested routes: http://guides.rubyonrails.org/routing.html#nested-resources

My Models:

class Paymethod < ApplicationRecord
  has_many :transactions
end

class Transaction < ApplicationRecord
  belongs_to :paymethod
end

and routes.rb

resources :paymethods do
    resources :transactions
end

rake routes gives me:

 paymethod_transactions GET    /paymethods/:paymethod_id/transactions(.:format)     transactions#index

But I always getting same output for any paymethod_id

GET aymethods/1/transactions

[
  {
    "id": 1,
    "amount": 10,
    "user_id": 21,
    "paymethod_id": 1,
  },
  {
    "id": 2,
    "amount": 1,
    "user_id": 21,
    "paymethod_id": 1,
  }
]

and same by: GET paymethods/2/transactions

[
  {
    "id": 1,
    "amount": 10,
    "user_id": 21,
    "paymethod_id": 1,
  },
  {
    "id": 2,
    "amount": 1,
    "user_id": 21,
    "paymethod_id": 1,
  }
]

So, why its not filtering the results by paymethod_id?

Btw, it works with rails like Paymethod.find(2).transactions

Here a controllers: https://gist.github.com/nilsigusi/f59e65dd34495e08eaee

actually its standard controllers, generated by creating a model with rails

Upvotes: 1

Views: 698

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

In your gist, you had this at line 59: ( https://gist.github.com/nilsigusi/f59e65dd34495e08eaee#file-gistfile1-txt-L59 )

@transactions = Transaction.all

Which return all transaction records, no condition applied.

Replace with this:

@transactions = Transaction.where(paymethod_id: params[:paymethod_id])

To get all the transaction records belonging to the paymethod.

Upvotes: 2

Related Questions