2010-11-21 67 views
1

我想執行一個簡單的查詢,但Datamapper似乎沒有返回正確的結果集。Datamapper沒有執行正確的查詢

這看起來很基本,沒有理由說是錯的。

我認爲這可能是一個語法問題。

class User 
has n, :answers 
property :id, Serial 
property :name, String 
end 

class Answer 
belongs_to :user 
has n, :topics, :through => Resource 
property :id, Serial 
property :text, Text 
end 

class Topic 
has n, :answers, :through => Resource 
property :name, String, :key => true 
end 

o=User.create(:name=>'tom') 
puts a=Answer.create(:user=>o, :text => 'a1', :topics => [ 
Topic.first_or_create(:name => 'aboutme'), 
Topic.first_or_create(:name => '@onetom') 
]) 

#THIS WORKS 
#puts Answer.all(:user => {:name => 'tom'}, :topics => [{:name => 'aboutme'}]) 

#THIS DOES NOT WORK 
#puts o.answers.all(:topics => [{:name => 'aboutme'}]) 

回答

3

您沒有使用正確的參數,如果您想爲關聯添加條件,則應使用點符號。我在這裏爲您製作了一個示例腳本:

https://gist.github.com/709867

+0

謝謝!問題解決了! = d – 2010-11-22 15:04:08

0

有有是在關係代碼中的錯誤的可能性(它看起來像你使用嵌套屬性插件?)

約DataMapper的一個好處是,你可以查閱一下查詢正在生成。只需將「.query」標記到任何集合的末尾,就可以獲取查詢對象。

Answer.all(:user=>{:name=>'tom'}, :topics => [{:name => 'aboutme'}]).query在這種情況下。

您還可以看到SQL查詢將通過執行產生如下:

q = Answer.all(:user=>{:name=>'tom'}, :topics => [{:name => 'aboutme'}]).query 
DataMapper.repository.adapter.send(:select_statement, q) 

給予一個開槍後回到它是否在做一些奇怪的或不(或者甚至發佈的查詢對象生成我可以看看)。