Ruby on rails 如何添加外键?Id';桌子上的桌子是空的
我有三张桌子。帖子,回复,喜欢。用户(尚未实现)可以发表帖子、回复并喜欢这些回复,还可以就他们喜欢的原因留下简短评论。当回复留在帖子中时,它会将帖子id(foregin_键)与回复id一起保存。但是,当对Like进行评论时,只会传递Like_id,而不会传递reply_id和post_id。与控制器无关,但我的调试器显示,在发布时,回复id和post_id在表单中为空。反正这是我的桌子 Post.rbRuby on rails 如何添加外键?Id';桌子上的桌子是空的,ruby-on-rails,Ruby On Rails,我有三张桌子。帖子,回复,喜欢。用户(尚未实现)可以发表帖子、回复并喜欢这些回复,还可以就他们喜欢的原因留下简短评论。当回复留在帖子中时,它会将帖子id(foregin_键)与回复id一起保存。但是,当对Like进行评论时,只会传递Like_id,而不会传递reply_id和post_id。与控制器无关,但我的调试器显示,在发布时,回复id和post_id在表单中为空。反正这是我的桌子 Post.rb has_may :replies has_many :likes 答复.rb has_man
has_may :replies
has_many :likes
答复.rb
has_many :likes
belongs_to :post
Like.rb
belongs_to :reply
belongs_to :post
迁移:
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :name
end
end
end
class CreateReplies < ActiveRecord::Migration
def change
create_table :replies do |t|
t.string :reply
t.belongs_to :post, index:true
end
end
end
class CreateLikes < ActiveRecord::Migration
def change
create_table :likes do |t|
t.integer :thumbs
t.string :comment
t.belongs_to :post, index:true
t.belongs_to :reply, index:true
end
end
end
class CreatePosts
喜欢的人需要被尊重。这样,您就不会有一个nil字段,您的“可爱”字段将只与回复或帖子相关。这实际上是何时使用多态性的一个经典示例 是的,这是去这里的路
您可以创建类似的模型,如下所示:
rails g model Like likeable_type:string likeable_id:integer...any other fields
然后在帖子和回复中,您可以这样做:
has_many :likes, as: :likeable