【问题标题】:DataMapper add property from another class to table of a different class.DataMapper 将另一个类的属性添加到不同类的表中。
【发布时间】:2016-10-20 11:07:20
【问题描述】:

我是使用 DataMapper 的新手,我只想将一个类的属性添加到另一个类的表中。我有两个类,如下所示: 我想将“user”类中的“handle”属性添加为“peep”表中的一列。我需要所有相关的 gem(不包括在下面),但我正在努力使用 DataMapper 语法。我尝试了has n, :userbelongs to 等的变体,但都导致'user_id has NULL values' 错误。

类“用户”:

class User

      include DataMapper::Resource

      property :id,               Serial
      property :email,            String, format: :email_address, required: true, unique: true
      property :handle,           String, required: true
  end

“窥视”类:

class Peep

  include DataMapper::Resource

  property :id,            Serial
  property :peep_content,  String
  property :created_at,    DateTime

end

【问题讨论】:

    标签: ruby database datamapper


    【解决方案1】:

    似乎与您的另一个问题重复:Data Mapper Associations - what code?

    但这是我的回答,当关联键不是常规的id..._id 时,您必须在添加关联时明确指定它,以便让DataMapper 知道如何为您查询关系。

    文档:http://datamapper.org/docs/associations.html 自定义关联部分。

    class User
      ...
      has n, :peeps, 'Peep',
        :parent_key => [ :handle ],      # local to this model (User)
        :child_key  => [ :user_handle ]  # in the remote model (Peep)
    end
    
    class Peep
      ...
      belongs_to :user, 'User',
        :parent_key => [ :handle ],      # in the remote model (Peep)
        :child_key  => [ :user_handle ]  # local to this model (User)
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 2021-10-13
      • 2013-02-10
      相关资源
      最近更新 更多