matthewalexander matthewalexander - 4 months ago 9
Ruby Question

Rails, API endpoint that returns all Items for which the current_user is the seller?

I need to set up an API end point that returns all the items for which the current_user is the seller. I'm doing my best to set up RESTful routes So for I have this:

routes.rb

Rails.application.routes.draw do
resources :users
resources :items
get "users/:id/items" => "users#items"
...


users_controller.rb

This returns all items where the seller_id column is equal to params[:id]. Eventually I'd like to add a buyer_id column to the items table and be able to filter for that as well - so I need to differentiate between buyer and seller. Obviously I am not doing that here.

class UsersController < ApplicationController

def seller_items
User.find(params[:id]).items
end
end


item.rb

class Item < ActiveRecord::Base
belongs_to :seller, :class_name => 'User', :foreign_key => 'seller_id'
enum status: {available: 0, pending: 1, sold: 2, expired: 3, banned: 4 }
end


user.rb

class User < ActiveRecord::Base
has_many :items, :class_name => 'Item', :foreign_key => 'seller_id'
end


schema.rb

ActiveRecord::Schema.define(version: 20160715043217) do

# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"

create_table "categories", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

create_table "items", force: :cascade do |t|
t.string "title"
t.text "description"
t.integer "price", limit: 8
t.integer "status"
t.datetime "published_date"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "seller_id"
end

add_index "items", ["seller_id"], name: "index_items_on_seller_id", using: :btree

create_table "users", force: :cascade do |t|
t.string "name"
t.decimal "latitude", precision: 9, scale: 6
t.decimal "longtitude", precision: 9, scale: 6
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

add_foreign_key "items", "users", column: "seller_id"
end

Answer

I would have separate controllers for each

routes.rb

get "users/:id/sold_items" => "sold_items#index"
get "users/:id/bought_items" => "bought_items#index"

Controllers

class SoldItemsController
  def index
    User.find(params[:id]).sold_items
  end
end

class BoughtItemsController
  def index
    User.find(params[:id]).bought_items
  end
end

models

class User < ActiveRecord::Base
  has_many :sold_items, :class_name => 'Item', :foreign_key => 'seller_id'
  has_many :bought_items, :class_name => 'Item', :foreign_key => 'buyer_id'
end

class Item < ActiveRecord::Base
  belongs_to :seller, :class_name => 'User', :foreign_key => 'seller_id'
  belongs_to :buyer, :class_name => 'User', :foreign_key => 'buyer_id'
  enum status: {available: 0, pending: 1, sold: 2, expired: 3, banned: 4 }
end
Comments