Sinatra和Datamapper - 将数据插入到一对多关系表中

时间:2010-07-18 16:32:26

标签: ruby sinatra datamapper

我有以下内容。每篇文章都有一个标题和一个正文,最多还有三个网址。我想将URL存储在不同的表中。因此,在我的形式,我有一个网站的领域。但是它们不起作用,只有文章字段才能输入数据库。我该如何指定它们?任何善良的灵魂能帮助我解决这个问题吗?

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 个答案:

答案 0 :(得分: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