has_many:通过抛出“RuntimeError:未知的绑定列。我们可以解释这个。”

时间:2014-02-26 22:04:25

标签: ruby-on-rails ruby sql-server activerecord

我正在尝试在Rails 4.0.1中的categories表和各种域模型(例如productsarticles)之间建立多对多关联,使用:through => :categorizations模型捕获关系,基于this Railscastthe guides,但我在某处出错了。我收到的错误消息 - Unknown bind columns. We can account for this. - 对我来说似乎并不特别有用。我不知道下一步该往哪里去。

class Categorization < ActiveRecord::Base
  establish_connection "#{Rails.env}_sqlserver_api"

  self.primary_key = 'id'

  belongs_to :category
  belongs_to :product
  belongs_to :article
end

class Article < ActiveRecord::Base
  establish_connection "#{Rails.env}_sqlserver_api"

  self.primary_key = 'id'

  has_many :categorizations
  has_many :categories, :through => :categorizations
end

class Category < ActiveRecord::Base
  establish_connection "#{Rails.env}_sqlserver_api"

  self.primary_key = 'id'

  has_many :categorizations
  has_many :articles, :through => :categorizations
end

class ArticlesController < ApplicationController
  respond_to :json

  def index
    @articles = Article.limit(params[:limit]).offset(params[:offset])
    respond_with @articles, each_serializer: ArticleSerializer
  end

  def show
    @article = Article.find(params[:id])
    respond_with @article, serializer: ArticleSerializer
  end
end

categorizations表看起来像这样......

id | category_id | category_name | categorized_type | categorized_id | created_at

我还是Rails的新手,所以我觉得很有可能我错过了一些明显的东西,所以我想我会联系社区。

1 个答案:

答案 0 :(得分:0)

要使用categorized_typecategorized_id列设置多态关联,您必须执行以下操作:

class Categorization < ActiveRecord::Base
  establish_connection "#{Rails.env}_sqlserver_api"

  self.primary_key = 'id'

  belongs_to :category
  belongs_to :categorized, :polymorphic => true
end

class Article < ActiveRecord::Base
  establish_connection "#{Rails.env}_sqlserver_api"

  self.primary_key = 'id'

  has_many :categorizations, :as => :categorized
  has_many :categories, :through => :categorizations
end

class Category < ActiveRecord::Base
  establish_connection "#{Rails.env}_sqlserver_api"

  self.primary_key = 'id'

  has_many :categorizations
  has_many :articles, :through => :categorizations, :source => :categorized, :source_type => 'Article'
end

有关详细信息,请参阅http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html