【问题标题】:DataMapper - create new value for relational DBDataMapper - 为关系数据库创造新价值
【发布时间】:2011-02-23 11:38:08
【问题描述】:

我有一个如下定义的关系数据库。如何输入一个新值,其中 B 属于 A。下面给出的代码似乎不起作用。

谢谢

class A
   include DataMapper::Resource

   property :id, Serial, :key => true
   property :name, String

   belongs_to :b
end

class B
   include DataMapper::Resource

   property :id, Serial, :key => true
   property :name, String

   has n, :as
end

创造新价值

 # Create new value
 post '/create' do
   a = A.new

   b = B.new
   b.attributes = params
   b.belongs_to = a #problem is here
   b.save

   redirect("/info/#{a.id}")
 end

【问题讨论】:

    标签: heroku sinatra datamapper


    【解决方案1】:

    #belongs_to 是一个模型(类)方法,您可以使用它来声明多对一关系。

    在您的示例中,您应该使用这样的“

    b.as << a
    

    这会将“a”实例添加到“as”集合并关联两个资源。

    【讨论】:

      【解决方案2】:

      [...]我如何输入一个新值,其中 B 属于 A。下面给出的代码似乎不起作用。

      您的代码暗示您在寻找属于 B 的 A,但您的问题是相反的,所以我将展示如何做到这一点,即 B 属于 A。

      class A
         include DataMapper::Resource
      
         property :id, Serial, :key => true
         property :name, String
      
         has n, :bs # A has many B's
      end
      
      class B
         include DataMapper::Resource
      
         property :id, Serial, :key => true
         property :name, String
      
         belongs_to :a, :required => false # B has only 1 A
      end
      

      注意你的 has 和 belongs_to 在这里颠倒了。我还在 belongs_to 端添加了 required => false ,因为如果在调用 save 之前 DataMapper 没有 b.a ,DataMapper 会默默地拒绝保存你的模型——一旦你对它感到满意,你可以根据需要删除所需的 false 。

      您可以通过以下两种方式使用该模型:

      # Create new value
       post '/create' do
         a = A.new
         a.save
      
         b = B.new
         b.attributes = params
         b.a = a
         b.save
      
         redirect("/info/#{a.id}")
       end
      

      这个例子通常和你的一样,但是我为 A 添加了一个保存调用。注意这可能不是必需的,我不适合测试这个特殊情况;过去我发现 DataMapper 会自动保存一些相关对象,但不会自动保存其他对象,因此我养成了始终明确保存以防止混淆的习惯。

       # Create new value
        post '/create' do
          a = A.create
          b = a.bs.create(params)
      
          redirect("/info/#{a.id}")
        end
      

      在第二个示例中,我在关系的多方调用 create,这将创建一个新 B,将其与“a”关联,设置给定的参数,并立即保存它。结果和前面的例子一样。

      如果您刚刚熟悉 DataMapper,您可能会发现将以下内容添加到您的应用程序会有所帮助:

      DataMapper::Model.raise_on_save_failure = true
      

      这将导致 DataMapper 在上述情况下为您提供错误和回溯,more info here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-15
        • 2011-05-16
        • 2013-01-11
        • 2014-06-30
        • 2013-01-22
        • 2013-04-30
        • 1970-01-01
        相关资源
        最近更新 更多