在具有两个foreign_keys的模型与另一个模型之间创建关联

时间:2013-05-14 16:32:37

标签: ruby-on-rails-3 foreign-key-relationship classname

在这个协会中苦苦挣扎,我有两种模式:图和市场,你可以在市场上与其他人交换你的玩具形象。

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

1 个答案:

答案 0 :(得分: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

然后我可以调用它(假设Figure类有名字:string)

<% @markets.each do |market| %>
  <%= market.figure_you_want_to_trade.name %>
  <%= market.figure_you_want_from_someone_else.name %>
<% end %>