2011-02-09 50 views
2

我讀的書簡單地通過Sitepoint軌道和給予這些模型:問題on Rails的燈具創建序列

story.rb

class Story < ActiveRecord::Base 
    validates_presence_of :name, :link 
    has_many :votes do 
     def latest 
      find :all, :order => 'id DESC', :limit => 3 
     end 
    end 

    def to_param 
     "#{id}-#{name.gsub(/\W/, '-').downcase}" 
    end 
end 

vote.rb

class Vote < ActiveRecord::Base 
    belongs_to :story 
end 

並給予這燈具

stories.yml

one: 
    name: MyString 
    link: MyString 

two: 
    name: MyString2 
    link: MyString2 

votes.yml

one: 
    story: one 

two: 
    story: one 

這些測試失敗:

story_test.rb

def test_should_have_a_votes_association 
    assert_equal [votes(:one),votes(:two)], stories(:one).votes 
    end 

def test_should_return_highest_vote_id_first 
    assert_equal votes(:two), stories(:one).votes.latest.first 
    end 

但是,如果我扭轉故事的順序,第一個斷言和提供對於第一個斷言的第一票,它通過

story_tes t.rb

def test_should_have_a_votes_association 
    assert_equal [votes(:two),votes(:one)], stories(:one).votes 
    end 

    def test_should_return_highest_vote_id_first 
    assert_equal votes(:one), stories(:one).votes.latest.first 
    end 

我複印了一切,因爲它是在書中,並沒有看到這方面的勘誤。我的第一個結論是,夾具正在創建自下而上的記錄,因爲它已被宣佈,但是這並沒有使任何想法成爲可能嗎?

有什麼想法?

編輯:我使用的Rails 2.9在運行RVM

+0

我以前從未見過這個錯誤(但我也非常喜歡ruby)。你有沒有試圖命名具有較少通用名稱的夾具中的物品?特別是故事。 – Augusto 2011-02-09 22:21:47

回答

8

您的燈具沒有得到ID爲1,2,3,等等。就像你所期望的 - 當你添加燈具,他們得到的ID基於(我認爲)在表名稱和燈具名稱的散列。對我們人類來說,它們看起來像隨機數字。

Rails這樣做,所以你可以很容易地引用其他裝置。例如,燈具

#parents.yml 
vladimir: 
    name: Vladimir Ilyich Lenin 

#children.yml 
joseph: 
    name: Joseph Vissarionovich Stalin 
    parent: vladimir 

實際上是在你的數據庫顯示像,特別是擴大從parent: vladimir在子模型parent_id: <%= ... %>

#parents.yml 
vladimir: 
    id: <%= fixture_hash('parents', 'vladimir') %> 
    name: Vladimir Ilyich Lenin 

#children.yml 
joseph: 
    id: <%= fixture_hash('children', 'joseph') %> 
    name: Joseph Vissarionovich Stalin 
    parent_id: <%= fixture_hash('parents', 'vladimir') %> 

注意 - 這是Rails的如何處理夾具之間的關係。

道德故事:不要指望你的燈具以任何特定的順序,並且不要指望:order => :id在測試中給你有意義的結果。反覆使用results.member? objX而不是results == [obj1, obj2, ...]。如果您需要固定ID,請自行對其進行硬編碼。

希望這會有所幫助! PS:列寧和斯大林實際上沒有關係。

+0

我會等待其他答案,但我想這是非常多的。我的意思是失敗消息指向以數字串表示的投票ID。通過硬編碼ID,你的意思是我應該在yml fixture文件中提供它們嗎? – yretuta 2011-02-10 01:57:05

1

澤維爾霍爾特已經給出了主要答案,但還想提到,可以強制軌道以固定的順序讀入燈具。

默認情況下軌分配它自己的ID,但你可以利用YAML omap規範指定有序映射

# countries.yml 
--- !omap 
- netherlands: 
    id:   1 
    title:  Kingdom of Netherlands 
- canada: 
    id:   2 
    title:  Canada 

因爲你是強迫命令,你也必須手動指定自己的ID,如如上所示。

另外我不確定這部分,但我認爲一旦你承諾重寫默認導軌生成的ID並使用你自己的,你必須對所有的下游引用做同樣的事情。

在上面的例子中,假設每個國家可以有多個領導者,你會做這樣的事情

# leaders.yml 
netherlands-leader: 
    country_id: 1 #you have to specify this now! 
    name: Willem-Alexander 

您需要手動指定指的是以前型號的ID(國家)