扶手:有什么不对的多与协会的条件加入? [英] rails : what's wrong with this multiple join with conditions on the associations?
问题描述
下面是我的模型:
class Deck < ActiveRecord::Base
belongs_to :game
has_many :deck_cards
end
class DeckCard < ActiveRecord::Base
belongs_to :card
belongs_to :deck
end
class Card < ActiveRecord::Base
end
下面是我的尝试发现:
DeckCard.all :joins => [:card, :deck], :conditions => {{:decks => {:game_id => @game.id}}, {:cards => {:present => true}}}
我不断收到错误:未定义的方法所有
的#Class:0x4b2a98>。我假设这是我的分析条件,误导性的错误。我下面的活动记录查询指南。我不知道是否要使用该协会的单数或复数形式。看起来像一个belongs_to的,你应该在用单数形式:哈希联接,但我不知道的:条件散列,所以我想这两个既不工作
I keep getting the error : undefined method for all
for #Class:0x4b2a98>. I'm assuming this is a misleading error from parsing my conditions. I'm following the guide for Active Record Query. I wasn't sure about whether to use the singular or plural form of the associations. Look like with a belongs_to, you're supposed to use singular form in the :joins hash, but I wasn't sure in the :conditions hash, so I tried both and neither worked.
在情况下,它是不明确的,我想要做的SQL是:
In case it isn't clear, what I'm trying to do in SQL is:
SELECT * from DeckCards
INNER JOIN decks on decks.id = deck_cards.deck_id
INNER JOIN cards on card.id = deck_cards.card_id
WHERE decks.game_id = 4
AND cards.present = true
我能够解决它现在使用 DeckCard.find_by_sql
,但它会是不错的找出原因的加入和关联条件不工作。
I'm able to get around it for now by using DeckCard.find_by_sql
, but it would be nice to figure out why the joins and conditions on associations isn't working.
我使用InstantRails的-2.0在Windows上,这是使用Rails 2.0.2
I'm using InstantRails-2.0 on windows, which is using Rails 2.0.2
编辑:(:所有...)而不是使用 DeckCard.find一些进展。我还编辑基于另一个答案的括号内。我最近code是
Edited : some progress using DeckCard.find(:all ...)
instead. I also edited the brackets based on another answer. My latest code is
DeckCard.find :all, :joins => [:card, :deck], :conditions => {:deck => {:game_id => @game.id}, :cards => {:present => true}}
这是产生以下错误:
which is producing the following error:
Unknown column 'deck_cards.decks' in 'where clause': SELECT `deck_cards`.* FROM `deck_cards` INNER JOIN `cards` ON `cards`.id = `deck_cards`.card_id INNER JOIN `decks` ON `decks`.id = `deck_cards`.deck_id WHERE (`deck_cards`.`decks` = '--- \n- :game_id\n- 5\n' AND `deck_cards`.`cards` = '--- \n- :present\n- true\n')
这些连接看起来是正确的,但不能在WHERE条件。我试着像一些不同的东西:甲板
或:甲板
在条件子句中,但没有运气。难道这是当前的ActiveRecord查询接口文档和条件,如何在2.0.2办呢?
The joins appear correct but not the WHERE conditions. I've tried a few different things like :deck
or :decks
in the conditions clause but no luck. Could this be another difference between the current ActiveRecord Query Interface docs and how conditions are done in 2.0.2?
谢谢!
推荐答案
您需要完成与该卡的型号贵会:
You need to complete your association with the Card model:
class Card < ActiveRecord::Base
has_many :deck_cards
end
编辑2 :试试这个:
DeckCard.find :all, :joins => [:card, :deck], :conditions => ["decks.game_id = ? and cards.present = ?", @game.id, true]
这篇关于扶手:有什么不对的多与协会的条件加入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!