2014-02-26 36 views
0

我在嘗試多到很多的Rails 4.0.1一個categories表和各種域模型(如productsarticles)之間的關聯來設置,通過使用:through => :categorizations模型捕捉的關係的基礎上,this Railscastthe guides,但我在某處出錯了。我收到的錯誤訊息 - Unknown bind columns. We can account for this. - 對我來說似乎並不特別有用。我不確定下一步該去哪裏。has_many:通過拋出「RuntimeError:Unknown bind columns。我們可以解釋這個。」

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

爲什麼你在每個模型上調用'establish_connection'? – Arjan

+0

爲什麼你在每個模型上調用'self.primary_key ='id''?這兩件事都是默認行爲。 – Arjan

+0

你可以顯示屬於錯誤消息的堆棧跟蹤嗎? – Arjan

回答

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

相關問題