2010-07-18 57 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