user3274539
user3274539

Reputation: 697

Ruby datamapper associations

I am just learning Ruby and datamapper, I have read the docs about associations from the official DataMapper site, but I still have two problems. First whenever I add associated object, I can not see it when displaying all objects. I have test class like:

class Test
  include DataMapper::Resource
  property :id, Serial
  property :name, String
  has 1, :phonen, :through => Resource
end

And then phonen class like:

class Phonen
  include DataMapper::Resource
  property :id, Serial
  property :number, String
  belongs_to :test
end

Then I am creating those 2 objects

@test = Test.create(
  :name => "Name here"
)

@phone = Phonen.create(
  :number => "Phone number"
)

@test.phonen = @phone
@test.save

And I want to display them like that (I want to return json)

get '/' do
  Test.all.to_json
end

What am I doing wrong? maybe its something with the to_json... I honestly don't know.. But I have one additional question to this topic, lets say I managed to connect those two classes, if I display JSON will I get Phonen { } or just inside class { }? I know its probably very easy question, but I can't figure it out. That's why I decided to ask you guys. Thanks for help

Upvotes: 0

Views: 135

Answers (1)

Jorge de los Santos
Jorge de los Santos

Reputation: 4633

Test.all Is returning an active record association in array form, not a hash, when you try to convert to json it's failing.

You can try:

render json: Test.all

As asked in this question:

Ruby array to JSON and Rails JSON rendering

Upvotes: 1

Related Questions