Ruby in Sinatra using DataMapper not retrieving associations
-
16-03-2021 - |
Question
For some reason my model does not contain the associated models I linked using has n.
My definition is as follows:
class Post
include DataMapper::Resource
has n, :comments
property :id, Serial
property :name, String
end
class Comment
include DataMapper::Resource
belongs_to :post
property :id, Serial
property :comment, Text
end
Then using the following route/code for some reason it throws an error because comments does not appear to be an attribute of user.
class MyApp < Sinatra::Application
get "/" do
@post = Post.get(1)
@post.comments.inspect
end
end
The tables DataMapper generate seem fine (using DataMapper.finalize & DataMapper.auto_upgrade!). It has a user table and a comment table that has a foreign key on posts.id.
Any advice on this?
Solution 2
Ok, it turns out i added a Time field to the comment declaration, like so:
class Comment
include DataMapper::Resource
belongs_to :post
property :id, Serial
property :time, Time
property :comment, Text
end
I'm also using MySQL which doesn't have the Time type and saves it as DateTime. When trying to retrieve the comments using Post.comments DataMapper tries to parse it as Time and dies.
Hope this saves somebody some headaches.
OTHER TIPS
What version of datamapper are you using?
You can create comments, save it and see what values is it storing in post_id?
Try to explicitly put the parent-key child-key relationship like this
belongs_to :post, :parent_key => [:id], :child_key => [:post_id]
property :post_id, Integer