Rails Routes - Having two different routes show same information

Viewed 81

I have two different models: User and Organization, orgs for short. I would like both to be able to create posts, so both have a one-to-many relationships with Post model.

I set my table as such:

create_table "posts", force: :cascade do |t|
    t.text "content"
    t.integer "likes"
    t.integer "user_id"
    t.integer "org_id"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end 

My routes:

      resources :users do
        resources :posts
      end

      resources :orgs do 
        resources :posts 
        resources :users
      end

My Outcome

// http://localhost:3001/api/v1/**users**/4/posts

[
  {
    "id": 3,
    "content": "This a user's post",
    "likes": 0,
    "user_id": 4,
    "org_id": null,
  },
  {
    "id": 5,
    "content": "This is an org's post",
    "likes": 0,
    "user_id": null,
    "org_id": 2,
  }
]

I am able to post as a user and as an org, however when I route to either my user or org, it shows the post for both.

Is there a way to show only user's post when route to user and only org's post when route to orgs?

2 Answers

You need to use .where queries example:

# showing posts for a user who's ID is 4:
user_4_posts = Post.where(user_id: 4)

user_4_posts will be and array of posts which have a user_id of 4

here's a link with more examples: Link

Hopefully this helps but maybe i misunderstood your question

Two separate controller actions are needed

We need to see your controller code. This is not an issue to do with your routes, that much. This more of a controller problem.

I would actually have two separate controllers: Posts::Organisations and another Posts::Users (don't use those names and the way I've set it up - I'm kinda annoyed with how it sits, but it might give you some ideas:)

# Untested code: i typed it in the editor, so there might be typos
# app/controllers/posts/organisations_controller.rb
module Posts
   class OrganisationsController < ApplicationController
     def index
       @organisation = Organisation.find(params[:organisation_id])
       @posts = @organisation.posts  # you might want to paginate this
     end
   end
end

# app/controllers/posts/users_controller.rb
module Posts
   class UsersController < ApplicationController
     def index
       @user = User.find(params[:user_id])
       @posts = @user.posts  # you might want to paginate this
     end
   end
end

And with your routes, you could have something like this:

  get "organisations/:organisation_id/posts", to: "posts/organisations#index", as: "organisation_posts"
  get "users/:user_id/posts", to: "posts/users#index", as: "user_posts"

The point is you probably need two separate controllers, or two separate actions to handle the situation where you want to see organisation posts, and user posts.

Related