我正在尝试在Rails 4.0.1中的categories
表和各种域模型(例如products
和articles
)之间建立多对多关联,使用:through => :categorizations
模型捕获关系,基于this Railscast和the 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的新手,所以我觉得很有可能我错过了一些明显的东西,所以我想我会联系社区。
答案 0 :(得分:0)
要使用categorized_type
和categorized_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。