【问题标题】:Sinatra and Datamapper - inserting data to a one to many relationship tableSinatra 和 Datamapper - 将数据插入到一对多关系表
【发布时间】:2010-07-19 04:35:16
【问题描述】:

我有以下。每篇文章都有一个标题和一个正文,以及最多三个网址。我想将网址存储在不同的表中。因此,在我的表单中,我有一个网址字段。但是它们不起作用,只有文章字段被输入到数据库中。我应该如何指定它们?有好心人能帮我解决这个问题吗?

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>

【问题讨论】:

    标签: ruby sinatra datamapper


    【解决方案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
    

    【讨论】:

    • 表格呢? 不起作用,输入没有保存到数据库中。
    • 在上面的例子中,他只是将“url”作为html表单中的字段。如果您要显示所有三个,那么您需要使用 html 表单中的所有三个来更新 url.new 构造函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 2016-05-07
    相关资源
    最近更新 更多