2013-05-14 96 views
0

與這個關聯一起掙扎,我有兩個模型:圖和市場,您可以在其中與其他人交易您的玩具圖。在一個有兩個外鍵的模型與另一個模型之間創建一個關聯

Figure class 
    figure_id:integer 
    name  :string 
    image_url:string 

Market class 
    market_id:integer 
    figure_you_want_to_trade_id   :integer #this should be associated with the figure_id 
    figure_you_want_from_someone_else_id:integer #this should be associated with the figure_id 

我該如何去做這種關聯?

我在想:

market.rb 
    has_many :figure_to_trade, :class_name => Figure, :foreign_key => figure_id 
    has_many :figure_you_want, :class_name => Figure, :foreign_key => figure_id 

figure.rb 
    belongs_to :figure_you_want_to_trade, :class_name => Market 
    belongs_to :figure_you_want_from_someone_else, :class_name => Market 

這是我收到的錯誤,當我試圖輸出這個:<%= market.figure_to_trade%>

的SQLite3 ::的SQLException:沒有這樣的柱:figures.figure_id:SELECT 「人物」 * FROM 「人物」 WHERE 「人物」, 「figure_id」= 1

回答

0

想通了

market.rb 
    belongs_to :figure_you_want_to_trade, :class_name => Figure 
    belongs_to :figure_you_want_from_someone_else, :class_name => Figure 

figure.rb 
    has_many :figure_to_trade, :class_name => Market, :foreign_key => :figure_you_want_to_trade_id 
    has_many :figure_you_want, :class_name => Market, :foreign_key => :figure_you_want_from_someone_else_id 

然後我可以通過它(假設圖類具有名稱:字符串)

<% @markets.each do |market| %> 
    <%= market.figure_you_want_to_trade.name %> 
    <%= market.figure_you_want_from_someone_else.name %> 
<% end %> 
相關問題