【问题标题】:How to create ActionController to get items with list of tags如何创建 ActionController 以获取带有标签列表的项目
【发布时间】:2016-05-14 07:46:43
【问题描述】:

数据库表,第一个表包含标签(id,name),第二个表包含项目和标签之间的关系。

  tags        
       id   name     
        1   TagA   
        2   TagB   
        3   TagC


 tags_items     
       item_id    tag_id
          1          1
          1          2
          1          3
          2          1
          2          3

活动记录:

  class Tag < ActiveRecord::Base
      has_many :tags_itemses

      validates_presence_of :name
      validates_length_of :name,  :maximum => 15
    end

    class TagsItems < ActiveRecord::Base
      has_many :tags
    end

在我的控制器中,我有索引方法:

def index
        items = TagItems.all.includes(:tags)
        render json: items,
               status: 200
      end

控制器应该如何获得以下 json?

    [{item_id :1, tags: [{id:1, name: TagA}, {id:2, name: TagB}, {id:3, name: TagC}]},
     {item_id :2, tags: [{id:1, name: TagA}, {id:3, name: TagC}]}]

【问题讨论】:

  • 您已经尝试过哪些代码来生成 json?

标签: ruby-on-rails actioncontroller


【解决方案1】:

您可以使用 include 选项自定义 JSON 输出:

class TagsController
  def index
    items = TagItems.all.includes(:tags)
    render json: items, includes: {
       tags: {
         only: [:id, :name]
       }
     }, status: 200
  end
end

但这可能会变得非常重复,并且会使您的控制器膨胀 - active_model_serializers 可以在这里提供帮助。

但是这仍然行不通,因为您的建模已经完成了!模型名称应始终为单数!如果tags_itemshas_and_belongs_to_many 关系,那么tags_items 将是合适的,但这是一种非常特殊的情况,因为这是一个没有关联模型的连接表。

您在这里想要的是使用has_many :through 关系在标签和项目之间设置多对多:

class Item < ActiveRecord::Base
  has_many :tag_items # you're not Gollum!
  has_many :tags, through: :tag_items
end

class Tag < ActiveRecord::Base
  has_many :tag_items
  has_many :items, through: :tag_items
end

class TagItem < ActiveRecord::Base
  belongs_to :tag
  belongs_to :item
end

您还需要更正表的名称!使用rails g migration RenameTagsItems 创建迁移并修改内容:

class RenameTagsItemsMigration < ActiveRecord::Migration
  def change
    rename_table :tags_items, :tag_items
  end
end

然后运行迁移 (rake db:migrate)。

【讨论】:

    猜你喜欢
    • 2019-01-24
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 2018-02-06
    相关资源
    最近更新 更多