2016-05-14 5 views
-1

データベーステーブル、最初のテーブルにはタグ(id、name)が含まれ、2番目のテーブルにはアイテムとタグの関係が含まれます。タグのリストを持つアイテムを取得するActionControllerの作成方法

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 

アクティブreocrds:コントローラはルックスはJSON次取得する

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

好きすべき方法:私のコントローラで

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 

を私は、インデックスメソッドがありますか?

[{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}]}] 
+0

すでにjsonを作成しようとしたコードはありますか? –

答えて

1

あなたはincludeオプションを使用してJSONの出力をカスタマイズすることができます。

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

しかし、これは、しかし非常に反復取得し、コントローラをbloatsすることができます - active_model_serializersはここに助けることができます。

モデリングが途切れているため、これはまだ機能しません。モデル名は常に単数でなければなりません! tags_itemshas_and_belongs_to_manyの関係であれば適切ですが、それは関連付けられたモデルのない結合テーブルなので非常に特殊なケースです。あなたがここに欲しい

gollum grammar

タグと項目の間、多くのセットアップに多くを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)を実行します。

関連する問題