0

我的代碼如下數據映射器的簡單關聯示例?

class City 
    include DataMapper::Resource 

    has n, :forums 

    property :id,   Serial 
    property :name,   String 
    property :parent_state, String 
    property :url,   String, :length => 255 
end 

class Category 
    include DataMapper::Resource 

    has n, :forums 

    property :id,   Serial 
    property :name,   String 
    property :url,   String, :length => 255 
end 

class Forum 
    include DataMapper::Resource 

    belongs_to :city 
    belongs_to :category 
    has n,  :posts 

    property :id,   Serial 
    property :rss,   String, :length => 255 
end 

class Post 
    include DataMapper::Resource 

    belongs_to :forum 

    property :id,   Serial 
    property :title,  String, :length => 255 
    property :date,   Date 
    property :time,   Time 
    property :body,   Text 
    property :url,   String, :length => 255 
    property :email,  String, :length => 255 

end 

我可以很容易地創建一個新的城市......(這是一個循環,我不認爲你真的關心看到裏面):

City.create(:parent_state => state, :name => citylink.content, :url => citylink.get_attribute('href')) 

但對於我的生活,我無法弄清楚我是如何創建一個新的論壇(所有論壇都是RSS屬性)。我試過用100種不同的方式編寫它,它要麼出錯或者只寫不到數據庫,我假設因爲沒有關聯,所以它拒絕寫入它。

我已經閱讀了DM教程和寫作相當多,我仍然不知道我會做什麼。

任何幫助非常感謝!

這是我最新的愚蠢樣品測試..大概的路要走......

city = City.get(:name => cityname) 
Forum.create(:city => city, :rss => "this works now") 

回答

1

應該僅僅是:

forum = city.forums.create(:rss => "whatever") 

如果這樣做不行,請檢查錯誤的任何明顯的跡象,你忽略了:

forum.errors.full_messages 

(假設你有dm驗證包括)

編輯|順便說一句,這是無效的:

city = City.get(:name => cityname) 

你可能想:

city = City.first(:name => cityname) 

cities = City.all(:name => cityname) 

當您使用.get,你只能通過主鍵,這樣:

city = City.get(1) 
+0

非常感謝,那是drivi我堅果。 – Tallboy