1

我正在尝试创建一组模型来表达用户创作帖子的帖子和用户,也可以喜欢帖子。以下代码似乎生成了正确的 SQL 表集,但是由于 User :posts 键中的冲突,最后一次查找失败 - 但我所有重命名它的尝试都失败/破坏了架构。

如何在不破坏其他任何内容的情况下将 User 中的最后一个 :posts (for likes) 重命名为 :post_likes?

require 'data_mapper'
require 'dm-sqlite-adapter'
require 'dm-noisy-failures'

DataMapper::Logger.new($stdout, :debug)
DataMapper::setup(:default, 'sqlite::memory:')

class Post
    include DataMapper::Resource
    belongs_to :author, 'User', :child_key => :author_id

    property :id,          Serial, :key => true
    property :message,     Text

    has n, :post_likes
    has n, :users, :through => :post_likes
end

class User
    include DataMapper::Resource

    property :id,    Serial, :key => true
    property :name,  String

    has n, :posts, :via => :author

    has n, :post_likes
    has n, :posts, :through => :post_likes # rename this to :post_likes
end

class PostLike 
    include DataMapper::Resource

    belongs_to :post, :key => true
    belongs_to :user, :key => true
end

DataMapper.finalize
DataMapper.auto_migrate!

john  = User.first_or_create(:name => 'John')
hello = Post.create(:message => 'Hello', :author => john)
tony  = User.create(:name => 'Tony')
fav   = PostLike.create(:user => tony, :post => hello)

puts tony.post_likes.first.post.to_json  # OK
puts hello.post_likes.first.user.to_json # OK
puts Post.first(:author => john).to_json # OK
puts john.posts.first.to_json            # fails (tries to look up via likes)

最后两个查询(第二个应该与第一个相同):

 ~ (0.000000) SELECT "id", "message" FROM "posts" WHERE "id" = 1 ORDER BY "id"                                       
{"id":1,"message":"Hello","author_id":1}                                                                             
 ~ (0.000998) SELECT "posts"."id", "posts"."author_id" FROM "posts" INNER JOIN 
              "post_likes" ON "posts"."id" = "post_likes"."post_id" INNER JOIN 
              "users" ON "post_likes"."user_id" = "users"."id" WHERE 
              "post_likes"."user_id" = 1 GROUP BY "posts"."id", "posts"."author_id" 
              ORDER BY "posts"."id" LIMIT 1                                                     
null                                                                                                                 
4

0 回答 0