Rails 4,has_many,返回特定类别

时间:2016-07-16 01:25:10

标签: ruby-on-rails ruby api rest rails-activerecord

我想知道在这种情况下是否应该创建一个类别控制器。目前我有一个具有#index和#show动作的物品控制器。我正在考虑在项目#index action中为特定类别添加过滤器 - 但是从类别控制器看起来要容易得多。以下是我的关联,它有效地建立了项目和类别之间的has_many关系:

class Category < ActiveRecord::Base
    has_many :categorizations
    has_many :items, :through => :categorizations
end

class Item < ActiveRecord::Base
    has_many :categorizations
    has_many :categories, :through => :categorizations
end

class Categorization < ActiveRecord::Base
    belongs_to :item
    belongs_to :category
end

我需要建立的API才能返回&#34;特定类别的可用项目列表&#34;。从类别控制器(我还没有)这样很容易:

category.items

这样做会更好,更安静吗?或者我应该在我的项目#index action中创建一个过滤器,目前看起来像这样:

# Returns full list of items
def index
    @items = Item.all
    render json: @items
end

当然,如果您有任何更有效/符合最佳做法的想法 - 请告诉我们!

谢谢!

编辑 - 一个解决方案:

我决定添加一个类别控制器,以便我可以使用以下相对路径访问特定类别的可用项目:

categories/:id/available_items

class CategoriesController < ApplicationController
    def available_items
        @available_items = Category.find(params[:id]).items.available
        render json: @available_items
   end
end

标准是返回与特定类别相关联的所有项目,并且状态为&#39;可用&#39;。

编辑:

我发现Item.where(category: 1)并未返回归入类别1的所有项目。请参阅下面的byebug控制台输出:

    1: class ItemsController < ApplicationController
    2:   # Returns full list of items
    3:   def index
    4:     @items = Item.all
    5:      byebug
=>  6:   end
    7: 

(byebug) Item.where(category: 1)
  Item Load (0.6ms)  SELECT "items".* FROM "items" WHERE "items"."category" = 1
#<Item::ActiveRecord_Relation:0x007fb5d1a37f08>
(byebug) Category.find(1).items
  Category Load (0.7ms)  SELECT  "categories".* FROM "categories" WHERE "categories"."id" = $1 LIMIT 1  [["id", 1]]
  Item Load (1.7ms)  SELECT "items".* FROM "items" INNER JOIN "categorizations" ON "items"."id" = "categorizations"."item_id" WHERE "categorizations"."category_id" = $1  [["category_id", 1]]
#<ActiveRecord::Associations::CollectionProxy [#<Item id: 1, title: "Gorgeous Cotton Pants", description: "Dolor dicta suscipit aut cupiditate quia officiis ...", price: 73960, status: 0, published_date: "2016-07-14 05:35:49", created_at: "2016-07-17 05:15:07", updated_at: "2016-07-17 05:15:07", seller_id: 1>, #<Item id: 5, title: "Sleek Marble Shoes", description: "Qui mollitia corporis qui placeat. Reiciendis ea s...", price: 35146, status: 0, published_date: "2016-07-14 05:45:02", created_at: "2016-07-17 05:15:07", updated_at: "2016-07-17 05:15:07", seller_id: 1>, #<Item id: 7, title: "Rustic Concrete Lamp", description: "Sit odio non exercitationem. Atque non sapiente vo...", price: 82016, status: 2, published_date: "2016-07-13 00:00:00", created_at: "2016-07-17 05:15:07", updated_at: "2016-07-17 05:15:07", seller_id: 1>, #<Item id: 10, title: "Awesome Wooden Table", description: "Possimus consequatur nulla. Quidem molestiae volup...", price: 59519, status: 2, published_date: "2016-07-09 00:00:00", created_at: "2016-07-17 05:15:07", updated_at: "2016-07-17 05:15:07", seller_id: 1>, #<Item id: 12, title: "Lightweight Concrete Bag", description: "Amet ullam assumenda eligendi consectetur quae. Bl...", price: 72081, status: 2, published_date: "2016-07-16 00:00:00", created_at: "2016-07-17 05:15:07", updated_at: "2016-07-17 05:15:07", seller_id: 2>, #<Item id: 13, title: "Mediocre Plastic Computer", description: "Excepturi modi est non qui iusto. Molestiae offici...", price: 94357, status: 2, published_date: "2016-07-15 00:00:00", created_at: "2016-07-17 05:15:07", updated_at: "2016-07-17 05:15:07", seller_id: 2>, #<Item id: 15, title: "Incredible Plastic Bag", description: "Vel voluptas ducimus soluta atque voluptatem eum. ...", price: 15661, status: 2, published_date: "2016-07-14 00:00:00", created_at: "2016-07-17 05:15:07", updated_at: "2016-07-17 05:15:07", seller_id: 2>, #<Item id: 16, title: "Lightweight Iron Watch", description: "Id sequi rerum dolor sit sunt nemo laborum. Omnis ...", price: 65306, status: 4, published_date: "2016-07-11 00:00:00", created_at: "2016-07-17 05:15:07", updated_at: "2016-07-17 05:15:07", seller_id: 1>, #<Item id: 17, title: "Rustic Linen Chair", description: "Explicabo qui ad nihil. Voluptatem placeat autem. ...", price: 39752, status: 4, published_date: "2016-07-04 00:00:00", created_at: "2016-07-17 05:15:07", updated_at: "2016-07-17 05:15:07", seller_id: 1>, #<Item id: 18, title: "Mediocre Copper Car", description: "Minus qui ut est non vero saepe. Qui sed quos et v...", price: 87765, status: 4, published_date: "2016-07-05 00:00:00", created_at: "2016-07-17 05:15:07", updated_at: "2016-07-17 05:15:07", seller_id: 1>]>

1 个答案:

答案 0 :(得分:1)

您提出的两个解决方案都是有效的,但让我们看看一些代码:

选项1 - Rails默认值

resources :categories do
  resources :items
end

# /categories/42/items/7

Rails会将其路由到ItemsControllercategory_id将负责对传入的resources :categories, :items class CategoriesController < ApplicationController def index @categories = Category.all end def show @category = Category.includes(:items).find params[:id] end end 执行某些操作。如果您的应用程序体系结构/逻辑没有真正以不同的方式完成,我会从这种方法开始。

选项2 - “显示类别”

items#show

如果显示控制器的概念自然会显示其项目,则此方法非常有用。鉴于多对多关系的典型特性,这可能不适合您的情况,但它实际上取决于上下文。

选项3 - 三个整洁控制器

如果您发现items#indexclass CategorizedItemsController < ApplicationController # ... end resources :categories resources :items scope '/categories/:category_id/' do resources :items, controller: :categorized_items end 方法开始变得过于有条件,我会考虑更改路由并添加控制器

Sub autocompletepayee()

    Dim cmd2 As New Odbc.OdbcCommand
    Dim dr As Odbc.OdbcDataReader
    Dim myquery As String
    myquery = "select payee from tbrequest"
    cmd2.CommandText = myquery
    cmd2.Connection = con
    dr = cmd2.ExecuteReader

    While dr.Read
        txtPayee.AutoCompleteCustomSource.Add(dr.GetString(0)) 'this is the line where the error prompt

    End While
    dr.Close()

对于加入您项目的其他开发人员而言,这一点并不那么明显,并开始对您的路线进行更具挑战性的推理,因此我不会从中开始。但是,如果您发现现有的控制器层次结构无法在RESTful路由的范围内表示您的操作,那么您应该毫不犹豫地采用这种解决方案。

干杯!