2015-10-28 21 views
1

我有三個表。帖子,回覆,贊。如果用戶(尚未實現)可以發佈帖子,回覆和贊同回覆,並留下他們爲什麼喜歡的簡短評論。當留言回覆時,它會將posts_id(foregin_key)和reply_id一起保存。但是,如果對Like進行評論,則只傳遞like_id而不傳遞reply_id和post_id。與控制器無關,但我的調試器顯示發佈時,表單中的reply_id和post_id是空白的。無論如何,這裏是我的桌子。如何添加外鍵?表中的Id是空的

Post.rb

has_may :replies 
has_many :likes 

Reply.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 

回答

1

喜歡需要是polymorphic。這樣,你不會有一個零字段,你'可愛'字段將只涉及到答覆,或一個職位。這實際上是什麼時候使用多態性的典型例子。

1

是的,polymorphic relations是去這裏的路。

您可以創建你的模型一樣,像這樣:

rails g model Like likeable_type:string likeable_id:integer...any other fields 
在帖子

然後和回覆你可以這樣做:

has_many :likes, as: :likeable