Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在Rails JSON API调用中包含两个联接表_Ruby On Rails_Ruby On Rails 3 - Fatal编程技术网

Ruby on rails 在Rails JSON API调用中包含两个联接表

Ruby on rails 在Rails JSON API调用中包含两个联接表,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,在尝试连接两个具有多态关系的表并在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 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
具体来说,我希望返回数据库中的每个项目及其类别。我已经尝试了我能想到的一切。非常感谢您的帮助。

您是否尝试过:

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

您的关联的名称实际上是:可链接的项目模型,而不是:类别,特别是因为它是一个属于的,所以它应该是:类别。

您尚未在项目模型中定义“类别”关系,因为它是可链接的。结账