2014-03-27 26 views
0

我正在试图加入两个表(使用多态的关系),当下面的活动记录协会的错误,包括在一个JSON API响应两个表中的所有数据:包括在Rails的JSON API调用连接表

Association named 'categories' was not found; perhaps you misspelled it? 

这里是我想打电话给控制器动作:

def index 

    @items = Item.includes(:categories) 
    respond_to do |format| 
     format.json { render :json => @items.to_json } 
    end 

end 

而且这里有两种模式,我想加入:

class Category < ActiveRecord::Base 

    attr_accessible :name 

    has_many :items, :as => :linkable 

end 

class Item < ActiveRecord::Base 

    attr_accessible :due_date, :linkable_id, :linkable_type, ... 

    belongs_to :linkable, :polymorphic => true, :counter_cache => true 

end 

具体而言,我想返回数据库中的每个项目及其类别。我尝试了所有我能想到的。任何帮助将不胜感激。

+1

您尚未在项目模型(可链接)中定义'类别'关系。结帐http://apidock.com/rails/ActiveModel/Serializers/JSON/as_json –

回答

0

你试过:

def index 
    @items = Item.includes(:linkable).where(:linkable_type => 'Category') 
    respond_to do |format| 
     format.json { render :json => @items.to_json(include: :linkable) } 
    end 
end 

贵会的名字居然是:可链接的项目模型,而不是:类(尤其是因为它是一个belongs_to的所以这将是:类)。