Dennis Best
Dennis Best

Reputation: 3654

Routes and index

In my Articles controller, I have the following index method:

def index
  @articles = Article.all
end

And in my routes.rb I have this:

resources :users do
  resources :articles, only: [:index]
end

This nicely gives me a route like this: localhost:3000/users/2/articles

But instead of showing a list of articles by user 2, it still shows all of them. What do I need to do to my index action?

Upvotes: 0

Views: 49

Answers (2)

jvperrin
jvperrin

Reputation: 3368

In your index action you should filter the articles you fetch by the user_id parameter:

def index
  @articles = if params[:user_id]
    user = User.find(params[:user_id])
    user.articles
  else
    Article.all
  end
end

Upvotes: 1

Jeet
Jeet

Reputation: 1380

Try this

@user = User.find(params[:id])
@articles = @user.articles

Upvotes: 0

Related Questions