Rails,返回current_user是卖方的所有项目的 API 端点



我需要设置一个 API 端点,该端点返回current_user是卖家的所有项目。我正在尽最大努力设置RESTful路由,所以我有这个:

路线.rb

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

users_controller.rb

这将返回seller_id列等于 params[:id] 的所有项目。最终,我想在项目表中添加一个buyer_id列,并且也能够对其进行过滤 - 所以我需要区分买方和卖方。显然,我在这里不这样做。

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

用户.rb

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

模式.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

我会为每个控制器提供单独的控制器

路线.rb

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

控制器

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

模型

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

相关内容

  • 没有找到相关文章

最新更新