2010-07-18 65 views
0

我有以下幾點。每篇文章都有一個標題和一個正文,最多三個網址。我想將這些網址存儲在不同的表格中。因此,在我的形式中,我有一個網站的網站。然而,他們不工作,只有文章字段被輸入到數據庫中。我應該如何指定它們?任何一種靈魂都能幫助我解決這個問題嗎?Sinatra和Datamapper - 插入數據到一對多關係表

class Article 
    include DataMapper::Resource 

    property :id,  Serial 
    property :title, String 
    property :body, Text 

    has n, :urls, through => Resource 
end 

class Url 
    include DataMapper::Resource 

    property :id,  Serial 
    property :url_01, String 
    property :url_02, String 
    property :url_03, String 

    belongs_to :article 
end 

post '/create' do 
    @article = Article.new(params[:article]) 
    if @article.save 
    redirect "/articles" 
    else 
    redirect "/articles/new" 
    end 
end 

-------------------------------------- 
<form action="/create" method="post"> 
    <p> 
    <label>Article Title</label> 
    <input type="text" name="article[title]"> 
    </p> 
    <p> 
    <label>Article Body</label> 
    <input type="text" name="article[body]"> 
    </p> 
    <p> 
    <label>Url</label> 
    <input type="text" name="article[url_01]"> 
    </p> 

    <p> 
    <input type="submit"> 
    </p> 

回答

1

我相信

, through => Resource 

,如果你正在做許多一對多的關係時,才需要。一對多,我認爲是你想要的,並不需要這樣做。查看the associations page上顯示的帖子和評論關係。

編輯點評:

如果我是你,我通常會命名我的表單字段和手動構建數據庫對象,例如:

<form action="/create" method="post"> 
    <p> 
    <label>Article Title</label> 
    <input type="text" name="title"> 
    </p> 
    <p> 
    <label>Article Body</label> 
    <input type="text" name="body"> 
    </p> 
    <p> 
    <label>Url</label> 
    <input type="text" name="url"> 
    </p> 

    <p> 
    <input type="submit"> 
    </p> 

然後:

post '/create' do 
    @article = Article.new(
     :title  => params[:title], 
     :body  => params[:body] 
) 
    @url = url.new(
     url_01 => params[:url] 
) 
    @article.url = @url 

    if @article.save 
    redirect "/articles" 
    else 
    redirect "/articles/new" 
    end 
end 
+0

那麼表格呢? 不起作用,輸入不會保存到數據庫中。 – 2010-07-18 17:52:09

+0

在上面的例子中,他只是將「url」作爲html表單中的字段。如果你顯示了全部三個,那麼你需要用html表單中的全部三個來更新url.new構造函數。 – 2010-07-19 14:39:12