DataMapper将另一个类的属性添加到另一个类的表中。

时间:2016-06-18 20:35:37

标签: ruby database datamapper

我是使用DataMapper的新手,只想在一个类中添加一个属性,在另一个类中添加一个表。我有两个课程,如下所示:我想添加'句柄'来自班级'用户'的财产,作为表格中的列,用于'窥视'。我已经要求所有相关的宝石(下面没有包含),但我正在努力使用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

上课' peep':

class Peep

  include DataMapper::Resource

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

end

1 个答案:

答案 0 :(得分:0)

似乎与您的另一个问题重复: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