Ruby数据映射器关联
我正在学习Ruby和datamapper,我已经阅读了官方datamapper网站上关于关联的文档,但是我仍然有两个问题。 首先,每当我添加关联对象时,在显示所有对象时都无法看到它。 我有这样的测试课:Ruby数据映射器关联,ruby,ruby-datamapper,Ruby,Ruby Datamapper,我正在学习Ruby和datamapper,我已经阅读了官方datamapper网站上关于关联的文档,但是我仍然有两个问题。 首先,每当我添加关联对象时,在显示所有对象时都无法看到它。 我有这样的测试课: class Test include DataMapper::Resource property :id, Serial property :name, String has 1, :phonen, :through => Resource end class Phone
class Test
include DataMapper::Resource
property :id, Serial
property :name, String
has 1, :phonen, :through => Resource
end
class Phonen
include DataMapper::Resource
property :id, Serial
property :number, String
belongs_to :test
end
然后是phonen类,如:
class Test
include DataMapper::Resource
property :id, Serial
property :name, String
has 1, :phonen, :through => Resource
end
class Phonen
include DataMapper::Resource
property :id, Serial
property :number, String
belongs_to :test
end
然后我创建这两个对象
@test = Test.create(
:name => "Name here"
)
@phone = Phonen.create(
:number => "Phone number"
)
@test.phonen = @phone
@test.save
我想这样显示它们(我想返回json)
我做错了什么?也许这是由于到_json
的原因。。。
我真的不知道。。
但是对于这个主题,我还有一个额外的问题,假设我成功地连接了这两个类,如果我显示JSON,我会得到Phonen{}
还是仅仅在类{}
内部?
我知道这可能是个很简单的问题,但我想不出来。这就是我决定问你们的原因。谢谢你的帮助。全部
正在以数组形式返回活动记录关联,而不是哈希,当您尝试转换为json时,它失败了
您可以尝试:
render json: Test.all
如本问题所述:
您不会嵌套关联,您必须创建一个序列化程序或视图,以便在测试类中重新创建phonen。也许你可以读一些关于jbuilder的东西。很酷,这正是我想要的,谢谢